In an Android project, how do I create/maintain a ...
# android
o
In an Android project, how do I create/maintain a CoroutineScope that has the lifetime of a logged in user? Something like a
UserScope
b
We have a user-scoped DI component, then it's easily inject separate coroutine scope for this component, works like a charm
☝️ 1
o
@bezrukov that's what I was thinking too, but when do you call coroutineScope.cancel()?
b
we have smth like UserComponentHolder that is placed in the application scope, and login/logout screens(or actions) triggers UserComponentHolder.login/logout. So basically when a user-scoped DI component changed/nullified, we call userComponent.userScope().cancel()
o
@bezrukov I see. Could you share how your coroutinescope is initialized? Is it
CoroutineScope(Dispatchers.Main)
?
Do you create a new type that inherits from CoroutineScope?
b
Yep, we create a separate type to be explicit (and to avoid dagger qualifiers):
Copy code
class UserScope(context: CoroutineContext = EmptyCoroutineContext) : CoroutineScope by CoroutineScope(context)

(it needs to be delegated because CoroutineScope(....) is a function and not a constructor.
Then we init it with supervisor job + Main.immediate + exception handler that logs an error
o
@bezrukov any reason why you want to avoid dagger qualifiers?
b
I think it more about project conventions, to me qualifiers are good for simple/rare use-cases, for use-cases like this (e.g. this coroutinescope is used in 100+ files in our project) we prefer a separate type. With qualifiers there is an implicit relationship between scope and qualifier which adds a complexity. But again, if your project widely uses qualifiers it is probably make sense
🧠 1