Which scope should be used to launch coroutines in...
# multiplatform
p
Which scope should be used to launch coroutines in kotlin multiplatform project? It's a class that generates some data for being displayed in compose desktop composable. I tryed with this:
Copy code
fun longJobFunction(): MutableList<BigData>{
    var bigDataList = mutableStateListOf<BigData>()
    CoroutineScope(Dispatchers.Main).launch {
        withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
            //fill bigDataList with big data
            Thread.sleep(5000)
        }
    }    
    return bigDataList
}
But it gives this exception
java.lang.IllegalStateException: Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android' and ensure it has the same version as 'kotlinx-coroutines-core'
j
the "trick" I believe is to use something like following....not sure if there's better/cleaner way https://github.com/joreilly/Confetti/blob/737a29e6e8d00387bc5ebc40873bf676576809bd/shared/build.gradle.kts#L82
Copy code
// hack to allow use of MainScope() in shared code used by JVM console app
              implementation("org.jetbrains.kotlinx:kotlinx-coroutines-swing:${Versions.kotlinCoroutines}")
p
But should I launch the coroutine that way? should I use MainScope and use tricks? is not a better way?
I mean... maybe Dispatchers.Main or CoroutineScope() are not the better ways to launch a coroutine in this scenario, I wonder if there are better ways
k
I usually get away with just using
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$version")
in commonMain and ``implementation("org.jetbrains.kotlinxkotlinx coroutines android$version")` in androidMain. Then I use
viewModelScope
in androidMain and a
MainScope
in iOS when launching from a
ViewModel
277 Views