Home > database >  Android Studio doesn't let me use repeatOnLifecycle
Android Studio doesn't let me use repeatOnLifecycle

Time:02-18

I want to observe data inside my fragment from viewModel, but Android Studio keeps triggering this warning. Can someone help with this problem? Can this problem somehow be related to Android Studio Bumbleblee's update? enter image description here

CodePudding user response:

set repeatOnLifecycle block inside activity and invoke ViewModel method from there

CodePudding user response:

When you write

viewLifecycleOwner.lifecycleScope.launch {
  repeatOnLifecycle(Lifecycle.State.STARTED) {
    // {code to collect from viewModel}
  }
}

The repeatOnLifecycle is an extension on a LifecycleOwner - here, you are implicitly using this - i.e., the Fragment's Lifeycle and most important not the Fragment View Lifecycle.

As seen in the documentation, you should explicitly be using viewLifecycleOwner.repeatOnLifecycle, which is exactly what the Lint check is telling you to use:

viewLifecycleOwner.lifecycleScope.launch {
  viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
    // {code to collect from viewModel}
  }
}
  • Related