Skip to content

Instantly share code, notes, and snippets.

@AndroidPoet
Last active October 22, 2022 07:27
Show Gist options
  • Save AndroidPoet/0d0db9818c8d82ca8aad18ccb1e00344 to your computer and use it in GitHub Desktop.
Save AndroidPoet/0d0db9818c8d82ca8aad18ccb1e00344 to your computer and use it in GitHub Desktop.
//function we call in our code
@Composable
@NonRestartableComposable
@OptIn(InternalComposeApi::class)
fun LaunchedEffect(
key1: Any?,
block: suspend CoroutineScope.() -> Unit
) {
val applyContext = currentComposer.applyCoroutineContext
remember(key1) { LaunchedEffectImpl(applyContext, block) }
}
//implementation of LaunchedEffect
internal class LaunchedEffectImpl(
parentCoroutineContext: CoroutineContext,
private val task: suspend CoroutineScope.() -> Unit
) : RememberObserver {
private val scope = CoroutineScope(parentCoroutineContext)
private var job: Job? = null
override fun onRemembered() {
job?.cancel("Old job was still running!")
job = scope.launch(block = task)
}
override fun onForgotten() {
job?.cancel()
job = null
}
override fun onAbandoned() {
job?.cancel()
job = null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment