Martyna Maron
04/23/2021, 12:21 PMmain
never returns 😕 All I need is for printSomethingWithDelay
to execute on a background thread, with no new coroutine, how can I achieve that?
fun main() {
runBlocking {
printSomethingWithDelay("something")
}
print("finished")
}
suspend fun printSomethingWithDelay(something: String) = withContext(AppDispatcher.appDispatcher){
delay(1000)
println(something)
}
object AppDispatcher {
val appDispatcher = Executors.newFixedThreadPool(1).asCoroutineDispatcher()
}
streetsofboston
04/23/2021, 12:25 PMZach Klippenstein (he/him) [MOD]
04/23/2021, 1:05 PMThread.sleep(1000)
println(“something”)
println(“finished”)
Martyna Maron
04/23/2021, 1:22 PMZach Klippenstein (he/him) [MOD]
04/23/2021, 1:30 PMMartyna Maron
04/23/2021, 1:32 PMMutex
, for example? 🤔louiscad
04/23/2021, 1:34 PMI don’t want to spin off new coroutines because I want to make sure all this communication with JS happens synchronously, but in the background.Launching a new coroutine or running the code in the same coroutine using
withContext
(or the invoke operator) doesn't impact anything when it comes the dispatcher. Even coroutines have nothing to do with the problem you're facing as Anton said. It's fine to use them here since it seems they are relevant to your use case (waiting for some code to run on a given dispatcher without blocking the main thread).
I think you simply need to keep a reference to the executor service so you can close/shutdown it at the end of your main
function, so the JVM doesn't stay alive.Zach Klippenstein (he/him) [MOD]
04/23/2021, 1:37 PMare you referring to
Mutex
, for example? 🤔
Sure, although it’s similar to non-coroutine mutex. More so things like channels, which have a nice api for passing messages between threads. Stuff you can do with non-coroutine primitives too, but it’s nice that these are shipped in what is effectively a standard library extension, supported on multiplatform, etc.