https://kotlinlang.org logo
#koin
Title
# koin
a

abbic

02/20/2023, 6:59 PM
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

Pedro Alberto

02/21/2023, 9:25 AM
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

arnaud.giuliani

02/21/2023, 4:20 PM
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

Pedro Alberto

02/22/2023, 8:12 AM
@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

abbic

02/22/2023, 1:34 PM
thanks!
p

Pedro Alberto

02/22/2023, 2:47 PM
@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

arnaud.giuliani

02/23/2023, 9:30 AM
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

Pedro Alberto

02/23/2023, 10:47 AM
ok seems we have to refactor 🙂
how can I explain this to my boss
a

arnaud.giuliani

02/23/2023, 2:55 PM
better testability, else assume some kind of coupling 🤷