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

Pablo

09/29/2020, 12:29 PM
I'm not using 
viewModel
 from now, so I don't have the coroutineScope on my 
presenter
 and one way I'm doing right now is I'm injecting with 
Dagger
 a 
CoroutineScope
 as follows :
Copy code
@Module
object CoroutineMainScopeModule{
  @Provides
  fun provideCoroutineMainScope() : CoroutineScope : MainScope() 
}
But I don't know if I'd have problems in the future, cna someone let me know the disvantages of doing that way? I also don't want to implement 
CoroutineScope
 on the presenter because I read it's a bad praxis, neither use 
GlobalScope
. I'm afraid because I don't have a 
Job
 there, well I mean yes, I have a 
ContextScope(SupervisorJob() + Dispatchers.Main)
 but in case I wanted to do things with different jobs, would be a problem there?
a

antonioleiva

09/29/2020, 12:36 PM
Where did you read that it's not good to implement CoroutineScope in the presenter? I'm interested in learning about that...
That's the solution I tend to use, and sometimes I also provide the
lifecycleScope
from the activity
👎 1
As the activity and presenter lifecycles are attached, it sounds like a good solution to me
g

gildor

09/29/2020, 12:48 PM
Injection of coroutine scope to constructor is right solution in general
I agree, implementation of coroutine scope almost always not the best idea, it essentially detached from any parent scope, so it becomes top level entity and cancellation of it must be handled by someone, and it not enforced by api One more problem, if you actually implement coroutine scope, anyone can launch any task on this scope or even worse, cancel it, which looks like unnecessary leaking of api which prevents scope encapsulation
Providing scope to constructor probably the best idea, but not how you do it,, create a new scope which not attached to anything, so it again top level entity which nobody manages, but getting it from lifecycle owner which creates this presenter is probably better idea
If you presenter is some application level singleton, create a new scope for it makes sense, if nobody ever cancel/destroy it, bit usually presenter is attached to some view, so following lifecycle (and as result use view-level lifecycle scope) of this view for view operations is right thing, and for presenter-lwvel operatins (of you want continue running coroutine if view is detached), used presenter-lelev scope, but how to get it depends on lifecycle of of presenter, as I wrote above
2 Views