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?

  • https://stackoverflow.com/questions/59521691/use-viewlifecycleowner-as-the-lifecycleowner – ADM Jan 13 '21 at 06:58
  • @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 –  Jan 13 '21 at 07:04

2 Answers2

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

Mohsen
  • 1,246
  • 9
  • 22
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.