https://kotlinlang.org logo
Title
u

ursus

10/28/2021, 1:58 AM
If you have an object which owns its CoroutineScope, should you collect flows of the object's dependencies in the
init
block, or should there be some explicit onCreate function instead? I'm not really a fan of the former, since now the ctor is called on whatever random thread DI decides However the latter you can mistakenly call mutiple times etc What's your preference?
s

streetsofboston

10/28/2021, 3:04 AM
In my opinion, if the object owns its CoroutineScope, then it should own its own lifecycle. It, and its CoroutineScope live and die together. Regardless how the object is created, when it comes alive, it CoroutineScope is alive and can start doing what it needs to do asap. I have no issue with it starting to collect (launchIn) its dependencies' flows right from its constructor.
1
And for the latter option, you risk not only calling it twice, you also risk forgetting to call it at all.
u

ursus

10/29/2021, 2:09 AM
Yea, but you can also forget to call clear, as we dont have destructors
Also testing is I think impossible if you collect streams in ctor, since you might emit a value synchronously, and in this case in test, there might not be anyone to observe it
s

streetsofboston

10/29/2021, 2:37 AM
Yes, all true and these are all things to be considered. Eg If you have a simple stateful flow to collect, it doesn't matter if anyone is listening at construction time or not. As usual in software engineering, it depends 😁