Tiger Oakes: How to replace onCommit, onActive, and onDispose in Jetpack Compose |
If you’re looking at some Jetpack Compose code or tutorials written last year, you might see the use of onCommit
, onActive
, and onDispose
. However, these functions are no longer present in Android’s developer documentation. They were deprecated in version 1.0.0-alpha11 in favor of SideEffect
and DisposableEffect
. Here’s how to use those new functions and update your code.
Composables should be side-effect free and not handle use cases such as connecting with a HTTP API or showing a snackbar directly. You should use the side effect APIs in Jetpack Compose to ensure that these effects are run in a predictable way, rather than writing it alongside your UI rendering code.
onCommit
with just a callbackThis simple use case has a simple update. Just use the new SideEffect
function instead.
// Before
onCommit {
sideEffectRunEveryComposition()
}
// After
SideEffect {
sideEffectRunEveryComposition()
}
onCommit
with keysIf you only want to run your side effect when keys are changed, then you should LaunchedEffect
if you don’t call onDispose
. (If you do, scroll down to the next section.)
// Before
onCommit(userId) {
searchUser(userId)
}
// After
LaunchedEffect(userId) {
searchUser(userId)
}
onCommit
with onDispose
Effects using onDispose
to clean up are now handled in a separate function called DisposableEffect
.
// Before
onCommit(userId) {
val subscription = subscribeToUser(userId)
onDispose {
subscription.cleanup()
}
}
// After
DisposableEffect(userId) {
val subscription = subscribeToUser(userId)
onDispose {
subscription.cleanup()
}
}
onActive
Rather than having a separate function for running an effect only on the first composition, this use cases is now handled by passing Unit
as a key to LaunchedEffect
or DisposableEffect
. You can pass any static value as a key, including Unit
or true
.
// Before
onActive {
search()
}
// After
LaunchedEffect(Unit) {
search()
}
onActive
with onDispose
// Before
onActive {
val subscription = subscribe()
onDispose {
subscription.cleanup()
}
}
// After
DisposableEffect(Unit) {
val subscription = subscribe()
onDispose {
subscription.cleanup()
}
}
Комментировать | « Пред. запись — К дневнику — След. запись » | Страницы: [1] [Новые] |