Skip to content

Instantly share code, notes, and snippets.

@yaraki
Created January 28, 2022 06:55
Show Gist options
  • Save yaraki/6ac68151d4c108bb39a74623b23ddea4 to your computer and use it in GitHub Desktop.
Save yaraki/6ac68151d4c108bb39a74623b23ddea4 to your computer and use it in GitHub Desktop.
// Copyright 2022 Google LLC.
// SPDX-License-Identifier: Apache-2.0
@Composable
fun LifecycleEffect(event: Lifecycle.Event, action: () -> Unit) {
val lifecycleOwner = LocalLifecycleOwner.current
val observer = LifecycleEventObserver { _, e ->
if (event == e) {
action()
}
}
DisposableEffect(Unit) {
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
}
@Composable
fun MyUi() {
LifecycleEffect(Lifecycle.Event.ON_RESUME) {
// Do something
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment