https://kotlinlang.org logo
#decompose
Title
# decompose
s

sigmadelta

01/25/2023, 3:27 PM
Hi everyone, first of all thanks for the great effort and time invested in the Decompose library as I’m already enjoying the benefits it provides. Second, I’m currently using it in a Compose-Desktop application, and I’m in a situation where I need to launch a few coroutines but I’m a little bit confused as to how the
main
&
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:
Copy code
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 again
a

Arkadii Ivanov

01/25/2023, 3:38 PM
There are multiple options. You can pass
Dispatchers.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.
a

Andrew Steinmetz

01/28/2023, 10:01 PM
Another trick you can do is make your own custom component context and provide the dispatchers through that. I did that once in this kmm app which helped reduce some boiler plate of always passing dispatchers in through the constructor directly. Then you can create a test component context that provides the test dispatchers.
7 Views