android / android/architecture-samples
Should life cycle owner be viewLifecycleOwner instead of the fragment instance?
- Dominant language
- Kotlin
- Stars
- 45.8k
- Forks
- 11.9k
- PR merge metrics
- No merged PRs in 30d
Description
I'm looking at this method from TasksFragment:
```kt
private fun setupNavigation() {
viewModel.openTaskEvent.observe(this, EventObserver {
openTaskDetails(it)
})
viewModel.newTaskEvent.observe(this, EventObserver {
navigateToAddNewTask()
})
}
```
I read [here](https://github.com/googlesamples/android-architecture-components/issues/47) that the life cycle owner should be viewLifecycleOwner instead of the fragment instance, like this:
```kt
private fun setupNavigation() {
viewModel.openTaskEvent.observe(viewLifecycleOwner, EventObserver {
openTaskDetails(it)
})
viewModel.newTaskEvent.observe(viewLifecycleOwner, EventObserver {
navigateToAddNewTask()
})
}
```
The explanation is a bit beyond my understanding, but I think it's because the fragment is never really destroyed on configuration changes, so using it as the life cycle owner results in duplicate observers.
Contributor guide
Research direction
Open TasksFragment and inspect setupNavigation, especially the two observers in the issue. Verify the lifecycle owner used for both navigation events and check behavior across fragment view recreation; the change is done when observers are tied to the active view lifecycle without duplicate navigation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- android, kotlin
- Domain
- mobile
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 45/100