Thomas Richtsfeld
07/04/2025, 6:07 AMval applicationScope = CoroutineScope(SupervisorJob() + otherConfig)
. No matter if using a DI framework or access the scope via the application object, I wonder why it is recommended to be a SINGLETON? Whenever someone calls applicationScope.cancel()
, the scope is dead and new coroutines can't be launched anymore. Meaning applicationScope.launch()
would not work anymore. This can lead to hard to debug bugs
Wouldn't it be better to inject newly created scopes each time I need a scope that lives longer than the VM? In the particular case of the article instead of val applicationScope = CoroutineScope(SupervisorJob() + otherConfig)
make it a function that returns a new instance. Or using Factory
instead of Single
in the case of Koin
Happy to hear your thoughts about that topicrkechols
07/04/2025, 6:38 AMapplicationScope.cancel()
be called any time other than when the application is shutting down? And then if the application has been shut down, how are new coroutines being launched?Thomas Richtsfeld
07/04/2025, 6:41 AMapplicationScope.cancel()
without anyone noticing. Cases like this can happen (e.g. bigger teams, unexperienced devs,...)
• And then if the application has been shut down, how are new coroutines being launched?
Not sure if I understand that question. When the application is shut down all the coroutines are cancelled. If it is launched again the coroutines are gone and would not continue running. You don't have access to them anymorerkechols
07/04/2025, 6:58 AMapplicationScope
got cancelled when it shouldn't have been" because there are more than a million ways you can always goof something up; I don't think it's the author's job to account for them all. Rather, they're setting forth a solution. I think the assumption is "if you have bugs preventing this from working correctly, you'll fix those bugs".
(My second question was rhetorical, trying to highlight that you shouldn't ever have both a canceled applicationScope
and more work to be done in that scope. Sorry for the lack of clarity)
If you are worried about applicationScope
being canceled when it shouldn't, then you certainly can try out some other solution such as a factory function to get you more transient scopes, but I don't know how that would affect performance, garbage collection, etc. But in general I think most people would prefer the singleton applicationScope
solution since it avoids the overhead of creating unnecessary new scopes. I'd be satisfied with a comment on its declaration saying "don't cancel this until total app shutdown" or similar.Thomas Richtsfeld
07/04/2025, 7:44 AMKamilH
07/04/2025, 12:53 PMBogdan Vladoiu Lbs
07/07/2025, 4:17 AM