ursus
01/10/2023, 4:09 PMcollectAsState()
vs collectAsStateWithLifecycle()
on a viewmodel state in a app where screens are fragments.
I found out, surprisingly, that they behave the same.
If I push a new fragment, then the current fragment’s view gets destroyed, therefore compose “instance” there dies, and nothing is collected (observed), so no need for the withLifecycle
Guess that is nice and ultimately expected.
However, what I found as well, is that the state collection stops as well when app goes to background (still using collectAsState, not the withLifecycle
How is this possible? Does compose have some implicit hooks into the Activity
? Since in this case the fragment’s view does not get destroyedManuel Vivo
01/10/2023, 4:21 PMcollectAsState
is used. If you use collectAsStateWithLifecycle
the flow collection stops until the app is in the foreground againursus
01/10/2023, 4:25 PMcollect {
if (inForeground) {
recompose(it)
}
}
ursus
01/10/2023, 4:26 PMManuel Vivo
01/10/2023, 4:27 PMursus
01/10/2023, 4:28 PMursus
01/10/2023, 4:28 PMManuel Vivo
01/10/2023, 4:30 PMwithLifecycle
but it's a good practice to use the fragment's view lifecycle when triggering coroutinesursus
01/10/2023, 4:31 PMursus
01/10/2023, 4:32 PMursus
01/10/2023, 4:33 PMfragmentManager.replace
,(as opposed to fragmentManager.add
?ursus
01/10/2023, 4:48 PMManuel Vivo
01/11/2023, 7:56 AMursus
01/11/2023, 1:14 PMursus
01/11/2023, 1:14 PMdazza5000
01/13/2023, 6:00 PMdazza5000
01/13/2023, 6:00 PMdazza5000
01/13/2023, 6:00 PMval homeState by viewModel.homeState.collectAsStateWithLifecycle(
viewLifecycleOwner,
Lifecycle.State.RESUMED,
)
val context = LocalContext.current
val nextScreen = homeState.nextScreen
val fragmentManager = getFragmentManagerFromContext()
Timber.i("lifecyclestate is ${viewLifecycleOwner.lifecycle.currentState}")
Timber.i("home is $nextScreen")
dazza5000
01/13/2023, 6:00 PMdazza5000
01/13/2023, 6:01 PM2023-01-13 11:53:07.788 17057-17103 FA co.well.wellapp.debug V Activity paused, time: 6877042
2023-01-13 11:53:07.928 17057-17057 HomeFragmentKt co.well.wellapp.debug I lifecyclestate is CREATED
2023-01-13 11:53:07.929 17057-17057 HomeFragmentKt co.well.wellapp.debug I home is Deeplink(deeplink=<wellapp://open/journeys>)
dazza5000
01/13/2023, 6:01 PMRESUMED
collection is occurring while lifecycle state is CREATED
dazza5000
01/13/2023, 6:02 PMcollectAsStateWithLifecycle
worksdazza5000
01/13/2023, 6:07 PMclass HomeFragment : BaseFragment() {
override val eventScreenName: Event.Screen = Event.Screen.Home
private val viewModel: HomeViewModel by viewModel()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
viewModel.verifyNextScreen()
return ComposeView(requireContext()).apply {
setContent {
HomeRoute(
viewModel = viewModel,
navController = findNavController()
)
}
}
}
}
ursus
01/13/2023, 6:07 PMdazza5000
01/13/2023, 6:08 PMursus
01/13/2023, 6:08 PMdazza5000
01/13/2023, 6:13 PM