0

I want to know how we can send the message from one thread to the main thread in kotlin. ps: Not on android. I don't want any android platform specific answer.

I've tried this in android platform as below

    private val uiThreadHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            (msg.obj as () -> Unit)()
        }
    }

And using this as

uiThreadHandler.obtainMessage(0, block).sendToTarget()

I want to achieve this on plain kotlin. How to achieve this thread communication in kotlin ?

MrCurious
  • 150
  • 3
  • 11
  • 1
    Possible duplicate of [inter thread communication in java](https://stackoverflow.com/questions/2170520/inter-thread-communication-in-java) – Salem Jan 18 '19 at 07:27
  • @Moira I am sending a block of code. How can I do that ? – MrCurious Jan 18 '19 at 07:34

2 Answers2

0

Simple way in Kotlin is to use Coroutines and suspend functions

class YourClass : CoroutineScope {

    // context for main thread
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + Job()

    fun toDoSmth() {
        launch {
            withContext(Dispatchers.IO) {
              // task(1) do smth in another thread
            }
              // do smth in main thread after task(1) is finished
        }
    }
}

Read also about Dispatchers

Artem Botnev
  • 2,267
  • 1
  • 14
  • 19
0

Message handling is strictly connected with Android. But you actually don't want to send a message to the handler. You'd actually only run code on that thread. So instead of using the messages like you're doing, you should just call post(Runnable):

val uiThreadHandler = Handler(Looper.getMainLooper())

uiThreadHandler.post {
    ...
}

To abstract this even further, you could use Kotlin Coroutines with the Android extension for Dispatchers.Main:

GlobalScrope.launch(Dispatchers.Main) {
    ...
}

The block will be scheduled on the Android main thread then. If you're not suspending anything within the block itself, which might be the case due to the fact that you're not using Coroutines right now, you might not need to worry about canceling the the Job being returned from launch.

tynn
  • 38,113
  • 8
  • 108
  • 143