I tend to go against the pattern of implementing `...
# coroutines
d
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
I dont mind implementing it since I mostly code against an interface, not the concrete class.
a
Do you mean that the implementor of an
interface
should implement
CoroutineScope
instead of the
interface
itself?
g
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
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
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
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.