How to design a CoroutineScope that active when us...
# coroutines
s
How to design a CoroutineScope that active when user login and cancel when user logout?
j
We recently did this by using a custom dagger component. Have a singleton manage the lifetime of the component and keep your CoroutineScope inside the component. Null the scope and cancel the coroutine as part of the logout process in your manager
👀 1
s
j
Yeah exactly like that article, keep your CoroutineScope in the component
UserManager doesn’t need to hold a reference to the scope, it can just grab it from the component and cancel when needed
🙌 1
s
Do I need to implement cache strategy like `viewModelScope`and
lifecyclescope
in
get()
?
Copy code
class UserSessionCoroutineScope : CoroutineScope {
    override val coroutineContext: CoroutineContext = 
        SupervisorJob() + Dispatchers.Main.immediate
}

val UserSessionComponent.userSessionScope: CoroutineScope
    get() {
        return UserSessionCoroutineScope()
    }
j
I’m not sure the most correct way to do it, but in my case I didn’t use an extension property. I used a dagger module to provide the CoroutineScope and then just inject it normally
And I access the scope from my manager through an EntryPoint (we use Hilt)
s
Got it! ty