简体   繁体   中英

Is there a way to launch a runnable within a Kotlin coroutine scope?

The context is that I need to work with some legacy Java code that uses the old world threading models. Thread pool executors, schedulers and runnables and threads.

However, my new code is all coroutine compatible.

So, given a runnable

val runnable = Runnable { 
    print("Hurray")
}

Is there a better way to run this runnable within a coroutine scope than the following which feels a little clumsy (you're really just going around the fact that you're trying to run a runnable and squeezing it in a coroutine)

GlobalScope.launch(Dispatchers.IO) { runnable.run() }

Is there a way interoperably work with runnables and coroutines?

Given the entirety of your input in the question, this is all you need to execute the Runnable :

runnable.run()

Now, if you implicitly assume there is some long-lasting computation or blocking I/O behind that runnable, and you don't want to block the current thread, then you must dispatch it to a background thread pool, which is exactly the same you would have to do in Java. In that case you would have to write what you call the "clumsy" idiom.

If your wish is to be able to just write runnable.run() and have Kotlin somehow, automagically, turn your blocking IO code into suspending, that is impossible for fundamental reasons. The Java code in that case executes native system calls which block the calling thread and there is no way around that fact.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM