How could I implement the message queue programming pattern in mpp?
“message queue programming pattern” means: an object, let’s call it
Counter
, provides some operations, e.g.
increase
and
decrease
, these operations could be called from main thread or other worker threads, but
Counter
will schedule these calls into its own single threaded message queue, then change its state, e.g. the
count
, it may also output its state through some callback, and the callback should be invoked on main thread.
On Android, we could using Handler or Executor to implement this pattern easily, I’m thinking if it’s possible to do it on Kotlin/Native. I want to develop a Kotlin multiplatform app and want to use this pattern in it.
I tried
worker
, but everything submitted to worker must be frozen, so I can’t update
Counter
’s state.
I also tried
coroutine
, but on Kotlin/Native, coroutine only works for main thread, although there is a preview version supporting multi-thread coroutine, but when I try to launch a coroutine on the dispatcher created by
newSingleThreadContext("test")
, it fails with “This dispatcher can be used only from a single thread test, but now in MainThread”.