Created
December 14, 2022 09:27
-
-
Save aartikov/a56cc94bb306e05b7b7927353910da08 to your computer and use it in GitHub Desktop.
Creates CoroutineScope for Decompose component
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
fun ComponentContext.componentCoroutineScope(): CoroutineScope { | |
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) | |
if (lifecycle.state != Lifecycle.State.DESTROYED) { | |
lifecycle.doOnDestroy { | |
scope.cancel() | |
} | |
} else { | |
scope.cancel() | |
} | |
return scope | |
} |
@zhombie
Hi. It's a great idea to make this an extension property and use InstanceKeeper for caching. Thank you!
By the way, the author of Decompose is @arkivanov. I am just a user and popularizer of the library.
Usually InstanceKeeper
instances outlive the hosting component. So scoping a job that captures the component would be a memory leak. Even though it's discouraged, you can still make all your components retained, so that you the original extension function would work just fine.
Btw, since Essenty version 1.3.0-beta01, Lifecycle#doOnDestroy {}
callback is automatically called if the lifecycle is already destroyed. So there is no need to check for DESTROYED
state manually.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@aartikov hi! Thanks for great library. How about ViewModel adapted viewModelScope extension for ComponentContext CoroutineScope. It is not the final version, just suggestion, in order to know what u think about it: