[英]LiveData, setValue in Activity and observe in fragment. Is it possible?
如何使用livedata,在activity中做setValue,在一個fragment中讀observe,有可能嗎? 我知道使用此代碼它會調用一個新實例兩次,但是如何正確執行呢?
視圖模型:
public class PongViewModel extends ViewModel {
private MutableLiveData<String> pongSections;
public MutableLiveData<String> getPongSections() {
if (pongSections == null) {
pongSections = new MutableLiveData<String>();
}
return pongSections;
}
}
主要活動:
// OnCreate
pongViewModel = new ViewModelProvider(this).get(PongViewModel.class);
pongViewModel.getPongSections().setValue("test");
分段:
pongViewModel = new ViewModelProvider(this).get(PongViewModel.class);
pongViewModel.getPongSections().observe(this, pongSections -> {
System.out.println("DATA !!!");
});
使用活動范圍的視圖模型從活動中獲取視圖模型,因為此時您是對的,您創建了一個新的視圖模型實例:
class YourFragment extends Fragment {
private val pongViewModel: PongViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//This should fire after updating in the activity now
pongViewModel.getPongSections().observe(this, pongSections -> {
System.out.println("DATA !!!");
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.