https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

Dico

04/03/2019, 6:35 AM
I tend to go against the pattern of implementing
CoroutineScope
in application components that use a coroutine lifecycle, favoring an approach using
private val scope = CoroutineScope(...)
That way the scope is not leaked by implementing the interface and it is in my opinion cleaner. It distinguishes better between using the scope and using the scope of a coroutine you created. What do you think? Why should we implement CoroutineScope the way it is suggested initially by structured concurrency?
s

spand

04/03/2019, 6:46 AM
I dont mind implementing it since I mostly code against an interface, not the concrete class.
a

addamsson

04/03/2019, 7:08 AM
Do you mean that the implementor of an
interface
should implement
CoroutineScope
instead of the
interface
itself?
g

gildor

04/03/2019, 7:18 AM
favoring an approach using
private val scope = CoroutineScope(...)
But how you cn control lifecycle of component? Just provide some method like cancel/close and delegate it to scope?
In general I think it’s fine to hide abstraction if it’s possible and not required for other components
👍 1
g

ghedeon

04/03/2019, 7:33 AM
Why should we implement
CoroutineScope
.
We don't have to. Check the ViewModel extension from ktx library. They (
@jw
?) did a pretty nifty trick there by going with composition, instead of inheritance.
Here is the
viewModelScope
extension: https://android.googlesource.com/platform/frameworks/support/+/androidx-master-dev/lifecycle/viewmodel/ktx/src/main/java/androidx/lifecycle/ViewModel.kt And here how it's being closed in ViewModel: https://android.googlesource.com/platform/frameworks/support/+/androidx-master-dev/lifecycle/viewmodel/src/main/java/androidx/lifecycle/ViewModel.java A bit hacky but I like it 🙂 It's
Closeable
interface + map of tags. Could be done for Rx as well, anything that has to be cleared.
d

Dico

04/03/2019, 9:03 PM
But how you cn control lifecycle of component? Just provide some method like cancel/close and delegate it to scope?
Yeah, exactly
That's an interesting approach, @ghedeon
g

ghedeon

04/03/2019, 9:32 PM
Yes, and pretty smart, for a public library. If they change their mind or something goes wrong with coroutines, the ViewModel interface will remain unaffected.