在一个 Looper 线程上的 CoroutineDispatcher

9
我有一个用于在数据库 Realm 上执行某些任务的辅助类。正如您所知,我们在使用 realm 时有一些限制,例如:
  1. 非循环线程上的 Realm 实例不会自动刷新。
  2. 仅可以在创建它们的线程上访问 Realm 对象。
我的 Helper 类扩展了 CoroutineScope,并使用以下代码提供了 CoroutineContext: Executors.newSingleThreadExecutor().asCoroutineDispatcher()
但我的问题是,在此 CoroutineScope 上的所有任务都在非循环线程上运行,因此我该如何创建运行在单个循环线程上的 ExecutorCoroutineDispatcher。
显然,我不想使用 Dispatchers.Main,因为它应该在我的数据库上执行任务。

4
要怎么样创建一个 val handlerThread = HandlerThread(name),然后启动它,再在它的 looper 上创建 handler,并将其转换为 dispatcher:Handler(handlerThread.looper).asCoroutineDispatcher() - Pawel
我已经测试过了,但是它抛出了这个异常:Caused by: java.lang.NullPointerException: Attempt to read from field 'android.os.MessageQueue android.os.Looper.mQueue' on a null object reference - Mahdi Yusefi
抱歉,你是对的。我还没有启动处理程序线程。 - Mahdi Yusefi
1个回答

6
虽然 @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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接