user221256
user221256

Reputation: 435

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

Upvotes: 7

Views: 4474

Answers (1)

Roman  Elizarov
Roman Elizarov

Reputation: 28688

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.

Upvotes: 9

Related Questions