Last active
October 22, 2022 07:27
-
-
Save AndroidPoet/0d0db9818c8d82ca8aad18ccb1e00344 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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