[英]LiveData observer fired multiple in fragment
I was trying to implement SignIn feature in a fragment
.我试图在
fragment
中实现登录功能。 Following is the code for that:以下是代码:
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
MainViewModel mainViewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
String email = ....;
String password = ....;
SignInLiveData signInStatusObserver = mainViewModel.getSignInStatusLiveData(email, password);
signInStatusObserver.observe(getViewLifeCycleOwer(), new Observer<Boolean>{
@Override
public void onChanged(Boolean isSignedIn) {
if(isSignedIn)
Toast.makeText(requireContext(), "SignIn Successful", Toast.LENGTH_LONG).show();
else
Toast.makeText(requireContext(), "SignIn Unsuccessful", Toast.LENGTH_LONG).show();
}
}
}
It is working fine but when I lock the phone and then unlock it (with the app on the screen), the Toast
message is show again.它工作正常,但是当我锁定手机然后解锁(使用屏幕上的应用程序)时,再次显示
Toast
消息。 Again when I lock and then unlock the device (for any number of time), the toast is shown again and again.当我再次锁定然后解锁设备(任意次数)时,吐司会一次又一次地显示。
Why is it happening like that?为什么会这样?
How to show the toast only once?如何只显示一次吐司?
I believe it goes like this in your case:我相信你的情况是这样的:
How to deal with it: to keep it short, pls check here https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150 (I am not the author)如何处理:为了简短起见,请在此处查看https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150 (我不是作者)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.