If I have a class in my app annotated with @ActivityRetained it makes sense to able to access a coroutine scope that will be canceled appropriately. It would be similar to the viewModelScope in a ViewModel.
Is this something that can be done or is it something that still needs to be implemented?
I was struggling with the same problem but finally I found a solution here
You can create your own CoroutineScope with passed lifecycle:
class RetainedLifecycleCoroutineScope(
val lifecycle: RetainedLifecycle,
) : CoroutineScope, RetainedLifecycle.OnClearedListener {
override val coroutineContext: CoroutineContext = SupervisorJob() + Dispatchers.Main.immediate
init {
lifecycle.addOnClearedListener(this)
}
override fun onCleared() {
coroutineContext.cancel()
}
}
And use it like this:
@ActivityRetainedScoped
class UseCase @Inject constructor(
activityRetainedLifecycle: ActivityRetainedLifecycle,
) {
private val coroutineScope = RetainedLifecycleCoroutineScope(activityRetainedLifecycle)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With