Looper 线程上的 CoroutineDispatcher

CoroutineDispatcher on a Looper Thread

我有一个帮手 class 可以在数据库 Realm 上做一些工作。如您所知,我们在使用 realm 时有一些限制,例如:

  1. Realm 实例不会在非循环线程上自动刷新。
  2. Realm 对象只能在创建它们的线程上访问

我的助手 class 扩展 CoroutineScope 并提供 CoroutineContext 我使用了这段代码 Executors.newSingleThreadExecutor().asCoroutineDispatcher()

但是我的问题是这个 CoroutineScope 上的所有作业都是 运行ning 在非循环线程上所以 我如何在单个活套线程上创建一个 ExecutorCoroutineDispatcher,它是 运行。

很明显我不想使用 Dispatchers.Main 因为它应该在我的数据库上做作业

尽管@Pawel 的评论已经解决了 OP 的问题,对于可能需要特定代码片段的人:

// prepare a HandlerThread and start it
val handlerThread = HandlerThread("MyThread")
handlerThread.start()
// obtain Handler from the HandlerThread's looper
val handler = Handler(handlerThread.looper)
// Now you can get CoroutineDispatcher from the Handler
val myDispatcher = handler.asCoroutineDispatcher()

或者很快使用作用域函数:

val myDispatcher = HandlerThread("MyThread")
    .apply { start() }
    .looper.let { Handler(it) }
    .asCoroutineDispatcher()