简体   繁体   English

LiveData 观察者在片段中多次触发

[英]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:我相信你的情况是这样的:

  1. You lock your device -> at some point fragment's view is destroyed (view model is not)你锁定你的设备->在某些时候片段的视图被破坏(视图 model 不是)
  2. You unlock your device and back to the app -> your fragment gets new view, tries to observe live data (remember view model is the same as in p1) -> the event gets emitted.您解锁设备并返回应用程序 -> 您的片段获得新视图,尝试观察实时数据(请记住视图 model 与 p1 中的相同)-> 事件被发出。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM