0

Let's imagine the following case: we have BottomNavigationView with Navigation Component and MVVM architecture.

In which case in Fragment this line of code will now work

onViewCreated()

viewModel.isActionDone.observe(viewLifecycleOwner) {
    doReaction()
}

but this code will?

private val observer = Observer<Boolean> {
    doReaction()
}

onViewCreated()

viewModel.isActionDone.observe(this, observer)

In my app, the second code works great, but the first code doesn`t work correctly: when I move to another element in the BottomNavigationView, the observer is called several times.

P.S. this code also calling observer several times.

viewModel.isActionDone.observe(viewLifecycleOwner, observer)

Сould you please help me understand what could be wrong with the first code?

2
  • @ADM, I know that I should use viewLifecycleOwner, but I still can't understand why using this does not bring multiple calls, and viewLifecycleOwner brings
    – user13201453
    Jan 13, 2021 at 7:04

2 Answers 2

0

it's because every time onStart() is called on your fragment, the livedata becomes active again and emits the last value again. you should use the Event class as a wrapper or you could use the SingleLiveEvent class which is now considered an anti pattern. you could read this for more information: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

4
  • it's because every time onStart() is called on your fragment, the livedata becomes active again and emits the last value again it's not true
    – IR42
    Jan 13, 2021 at 7:50
  • 2
    @IR42 yes it is true Jan 13, 2021 at 8:33
  • SingleLiveEvent has been an official anti-pattern since about 2018 Jan 25, 2021 at 16:27
  • @EpicPandaForce yeah, I wasn't a developer back then :D
    – Mohsen
    Jan 25, 2021 at 16:35
0

It's because When you move to another fragment, NavController destroy the view and stop the fragment and when you back to the first fragment, fragment will be started and view will be created again.

So when you're using "viewLifecycleOwner" for observe, your LiveData emit the last value each time when you back to the first fragment. but when using "this", it does not.

So you should think about your business that you need have emits each time your view created or each time fragment created and use suitable LifecycleOwner.

I home it help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.