I have some code which uses single HandlerThread with Handler to send messages to it. Is there any way to do this with coroutines? I don't want to create new coroutine every time, I just want to execute blocks of code on the HandlerThread. Please help
Android-specific approach: Create new Android Handler , use Handler. asCoroutineDispatcher() extension to convert it to the coroutines context extension. Then you'll be able to use launch to send your blocks of code for execution. It is Ok to create new coroutine every 2 seconds.
Kotlin coroutines use dispatchers to determine which threads are used for coroutine execution. To run code outside of the main thread, you can tell Kotlin coroutines to perform work on either the Default or IO dispatcher. In Kotlin, all coroutines must run in a dispatcher, even when they're running on the main thread.
Lightweight: You can run many coroutines on a single thread due to support for suspension, which doesn't block the thread where the coroutine is running. Suspending saves memory over blocking while supporting many concurrent operations. Fewer memory leaks: Use structured concurrency to run operations within a scope.
A co routine is asked to (or better expected to) willingly suspend its execution to give other co-routines a chance to execute too. So a co-routine is about sharing CPU resources (willingly) so others can use the same resource as oneself is using. A thread on the other hand does not need to suspend its execution.
If you are looking to execute a block of code in the main Android thread, then you can use UI
context from kotlinx-coroutines-android
module like this:
launch(UI) {
... // this block of code will be executed in main thread
}
The above snippet sends a message to the main handler to execute your code.
If you looking for a custom handler thread for background work, then you can create a single-threaded context in one of two ways.
Generic approach: Use newSingleThreadedContext()
like this:
val ctx = newSingleThreadedContext() // define your context
launch(ctx) { ... } // use it to submit your code there
Android-specific approach: Create new Android Handler
, use Handler.asCoroutineDispatcher()
extension to convert it to the coroutines context extension. Then you'll be able to use launch
to send your blocks of code for execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With