Looper 线程上的 CoroutineDispatcher

Mah*_*efi 11 multithreading android realm kotlin kotlin-coroutines

我有一个帮助程序类,用于在数据库领域上执行一些工作。如您所知,我们在使用领域时有一些限制,例如:

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

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

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

很明显我不想使用,Dispatchers.Main因为它应该在我的数据库上完成工作

hat*_*ata 8

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

// 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()
Run Code Online (Sandbox Code Playgroud)

或者很快使用 Scope 函数:

val myDispatcher = HandlerThread("MyThread")
    .apply { start() }
    .looper.let { Handler(it) }
    .asCoroutineDispatcher()
Run Code Online (Sandbox Code Playgroud)