'Correct way to handle fragment's flow in the viewModel
I have a Fragment with a ViewModel.
In the Fragment I have a View which exposes a coroutine flow and I want to handle the collection within the ViewModel, and obviously I'm not going to reference the View to the ViewModel.
My idea was basically at the fragment onViewCreated:
view.flow
.onEach(viewModel::collect)
.launchIn(viewModel.viewModelScope)
This works, but... is this a good implementation? Or is there a better way to achieve my goal?
Solution 1:[1]
I believe you can use a standard fragment's scope not viewmodelScope
viewLifecycleOwner.lifecycleScope from androidx.lifecycle:lifecycle-runtime-ktx:2.2.0 dependency.
like this
view.flow
.onEach(viewModel::collect)
.launchIn(viewLifecycleOwner.lifecycleScope)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Petr Kubá? |
