Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coroutine scope for @ActivityRetained classes?

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?

like image 323
niqueco Avatar asked Aug 14 '26 12:08

niqueco


1 Answers

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)
}
like image 114
blackr4y Avatar answered Aug 16 '26 08:08

blackr4y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!