hi! how can i, in a jvm desktop application, provi...
# koin
a
hi! how can i, in a jvm desktop application, provide a coroutineScope scoped to the lifecycle of the app via koin?
just found something, might this
Copy code
factory { SupervisiorJob() }
single { CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + get<SupervisorJob>()) }
do the trick for me?
or maybe rather just
single { CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + SupervisorJob()) }
p
both should be Factory
and I did a my own Scope Type and you might want to have a supervisor job accessible
i.e.
Copy code
factoryOf(::MainScope)
Copy code
class MainScope: CoroutineScope {
    val supervisorJob: CompletableJob = SupervisorJob()
    override val coroutineContext: CoroutineContext
        get() = supervisorJob + Dispatchers.MAIN

}
you might need to also create abstraction on scheduler so when you go to unit test this is easier
not sure if @arnaud.giuliani has better way of achieving this
a
you can have the default dispatchers referenced in Koin, and request it when you need
for example here https://github.com/InsertKoinIO/nowinandroid, we can inject the default dispatchers from Koin
I would suggest to not use DI for Coroutines Scope configuration. or at least use injection by constructor if possible
p
@arnaud.giuliani can you refer the class so I can see a sample ? we use constructor injection but then when we need to test the class we need also mock the CorutineScope
after that, it’s used in cosntructor everywhere
just need to override the Dispatcher definition in test
a
thanks!
p
@arnaud.giuliani Why you don't recommend to have?
Copy code
factory {
     MainScope()
}
The thing why we went this way is that don't need to define every time where use the CoroutineScope. It becomes easier to use but if there is any side effect I would like to know.
a
I would avoid mixing Concurrency with DI as you are coupling them. In a unit test, it becomes less “unit” then, as you need DI container. But it’s ok to have default dispatchers in DI for constructor injection
p
ok seems we have to refactor 🙂
how can I explain this to my boss
a
better testability, else assume some kind of coupling 🤷