sigmadelta
01/25/2023, 3:27 PMmain
& io
`CoroutineContext`s are defined. On the documentation page (https://arkivanov.github.io/Decompose/component/scopes/#creating-a-coroutinescope-in-a-component) I found following sample:
fun CoroutineScope(context: CoroutineContext, lifecycle: Lifecycle): CoroutineScope {
val scope = CoroutineScope(context)
lifecycle.doOnDestroy(scope::cancel)
return scope
}
fun LifecycleOwner.coroutineScope(context: CoroutineContext): CoroutineScope =
CoroutineScope(context, lifecycle)
class SomeComponent(
componentContext: ComponentContext,
mainContext: CoroutineContext,
private val ioContext: CoroutineContext,
) : ComponentContext by componentContext {
// The scope is automatically cancelled when the component is destroyed
private val scope = coroutineScope(mainContext + SupervisorJob())
fun foo() {
scope.launch {
val result =
withContext(ioContext) {
"Result" // Result from background thread
}
println(result) // Handle the result on main thread
}
}
}
In the SomeComponent
constructor you are passing mainContext
and ioContext
. Do these need to be defined in the RootComponent
or just the parent component? And aside from that, how exactly are they instantiated?
Thanks againArkadii Ivanov
01/25/2023, 3:38 PMDispatchers.Main.immediate
or <http://Disaptchers.IO|Disaptchers.IO>
(or any other dispatcher) directly when calling the function. Or you can also pass dispatchers via component constructors. You can also do the following - SomeComponent(ioContext: CoroutineContext = <http://Dispatchers.IO|Dispatchers.IO>)
. You can substitude a dispatcher with TestDispatcher
in unit tests.Andrew Steinmetz
01/28/2023, 10:01 PM