Skip to content

Instantly share code, notes, and snippets.

@aartikov
Created December 14, 2022 09:27
Show Gist options
  • Select an option

  • Save aartikov/a56cc94bb306e05b7b7927353910da08 to your computer and use it in GitHub Desktop.

Select an option

Save aartikov/a56cc94bb306e05b7b7927353910da08 to your computer and use it in GitHub Desktop.
Creates CoroutineScope for Decompose component
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
}
@aartikov

Copy link
Copy Markdown
Author

@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.

@arkivanov

arkivanov commented Nov 27, 2023

Copy link
Copy Markdown

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.

@arkivanov

Copy link
Copy Markdown

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