ceedee
10/18/2023, 7:36 AMrepeatOnLifecycle
for Flow collection within onViewCreated
of Fragments.
But there’s a catch to it: when I navigate to another Fragment, the previous Fragment goes to ON_DESTROY_VIEW
but returns to ON_VIEW_CREATED
state when I navigate back to it.
Since repeatOnLifecycle
will only fully terminate itself when the Fragment reached ON_DESTROY
state, the call to repeatOnLifecycle
in onViewCreated
will spawn a DUPLICATE Flow collection. When I repeat this navigation / back navigation, even more Flow collections will add up.
The solutions I considered are:
a) using asLiveData()
in the ViewModel
b) moving repeatOnLifecycle
calls to onCreate
of the Fragment
But I wonder why Google recommends using repeatOnLifecycle
in onViewCreated
. Can anyone shed some light on this?zsmb
10/18/2023, 7:47 AMrepeatOnLifecycle
on viewLifecycleOwner
as described in the article, then the collection should be tied to the lifecycle of the Fragment's view, which means that it will be terminated when onDestroyView
happens.Robert Williams
10/18/2023, 8:42 AMRobert Williams
10/18/2023, 8:43 AMAlbert Chang
10/18/2023, 10:22 AMceedee
10/19/2023, 1:20 PMonDestroyView
we can get back to onViewCreated
) multiple repeatOnLifecycle
calls are issued which add up one after the other.
@Robert Williams Even if the Flow
from the ViewModel is a StateFlow
, still multiple collections will be launched which lead to multiple UI updates which is a bad thing since my application will become slower and slower after each navigation back to that Fragment.
I still think, that onCreateView
is the wrong place to call repeatOnLifecycle
.Robert Williams
10/19/2023, 1:37 PM* Runs the given [block] in a new coroutine when[Lifecycle] is at least at [state] andthis
* suspends the execution until[Lifecycle] is [Lifecycle.State.DESTROYED].this
Robert Williams
10/19/2023, 1:39 PMviewLifecycleOwner
scope the old repeatOnLifecycle will just return and the coroutine will be cleaned up on destroy view and the newly started one will be the only collectionceedee
10/20/2023, 12:58 PMhttps://miro.medium.com/v2/resize:fit:952/1*UWTA4pWxMjz32Kisy0sjhQ.png▾
onDestroyView
but NOT onDestroy
. From there, it can re-enter onViewCreated
on back navigation. Thus, active repeatOnLifecycle
calls will add up. So still, I believe the documentation is wrong in this point.Robert Williams
10/20/2023, 1:00 PMviewLifecycleOwner
scope: https://cs-ibrahimyilmaz.medium.com/viewlifecycleowner-vs-this-a8259800367bRobert Williams
10/20/2023, 1:02 PMceedee
10/20/2023, 1:56 PMviewLifecycleOwner
part because I had lifecycleOwner
in front of my eyes…
All explanations totally make sense, thank you!