我有一个奇怪的问题。在我的代码中,我在视图模型中观察到类型为MutableLiveData
的String
,并将上下文显示为Toast。当我在AVD中运行它时,烤面包被显示了一次以上,即MutableLiveData
被观察了一次以上。但是,当我在Mobile中运行相同的代码时,toast仅显示一次(按预期工作)。
代码(片段):
if(!viewModel.messageDisplayed) {
viewModel.MessageStatus.observe(viewLifecycleOwner, Observer {
it.toast(context)
viewModel.messageDisplayed = true // I'm using this variable to avoid displaying the toast multiple
//times but it does not work in the emulator
})
}
代码(ViewModel):
val MessageStatus = MutableLiveData<String>()
fun fireStoreOperations(){
//fireStore Operations
.addOnSuccessListener{
messageDisplayed= False
MessageStatus.value = "Message to be displayed"
}
}
您可以将观察者放在片段的onActivityCreated
中。所以看起来像
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewModel.MessageStatus.observe(viewLifecycleOwner, Observer {
it.toast(context)
viewModel.messageDisplayed = true
})
}