Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HandlerThread replacement in Coroutines

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

like image 243
user221256 Avatar asked Apr 14 '18 10:04

user221256


People also ask

How do you replace coroutine handlers?

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.

What are dispatchers in coroutines?

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.

Can coroutines run on 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.

Why coroutines are better than threads?

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.


1 Answers

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.

like image 195
Roman Elizarov Avatar answered Sep 22 '22 01:09

Roman Elizarov