You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Because the View lifecycle is odd, we either need to wait until onViewCreated in order to access it, or we need to use viewLifecycleOwnerLiveData. Using the former, the developer must use ordinary lifecycle callback functions in order to guarantee the View's existence. This is inconsistent with the rest of lifecycle coroutines, which could be executed from inside init { }.
The alternative approach of observing viewLifecycleOwnerLiveData seems better. It allows the use of init { }. Also, since onViewCreated must happen after onAttach(), this means that an AAC viewModel initialized via by viewModels may be accessed safely. This means we can write the following:
classMyFragment @Inject constructor(
coroutineScope:MainImmediateCoroutineScope
) : Fragment {
val viewModel:MyViewModel by viewModels()
init {
coroutineScope.withViewLifecycle { // this: ViewLifecycleCoroutineScope// safely reference this directly inside the constructor because this will never invoke before onAttach
viewModel.someFlow.onEach {
// ...
}.launchOnStart() // ViewLifecycleCoroutineScope-specific functions for lifecycle-aware collection of Flow
}
}
}
The text was updated successfully, but these errors were encountered:
Fragment
's double lifecycle issue affectsLifecycleCoroutineScope
(Androidx's or Dispatch's) as well.Consider this example from the official docs:
Because the
View
lifecycle is odd, we either need to wait untilonViewCreated
in order to access it, or we need to useviewLifecycleOwnerLiveData
. Using the former, the developer must use ordinary lifecycle callback functions in order to guarantee theView
's existence. This is inconsistent with the rest of lifecycle coroutines, which could be executed from insideinit { }
.The alternative approach of observing
viewLifecycleOwnerLiveData
seems better. It allows the use ofinit { }
. Also, sinceonViewCreated
must happen afteronAttach()
, this means that an AACviewModel
initialized viaby viewModels
may be accessed safely. This means we can write the following:The text was updated successfully, but these errors were encountered: