如何使用looper创建后台线程 [英] How to create a background thread with a looper

查看:49
本文介绍了如何使用looper创建后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以与我可以传递给 subscribeOn(AndroidScheduler.from(/backgroundThreadWithLooper/)) 的 Looper 共享后台线程的实现.

Can someone please share the implementation of a background thread with a Looper that i can pass to the subscribeOn(AndroidScheduler.from(/backgroundThreadWithLooper/)).

我需要这个,因为我正在尝试实现一个 DBService 类,该类在后台运行其所有操作,同时仍然获取实时对象更新.因此,当我应用 addChangeListener 时,会抛出异常:

I need this because i am trying to implement a DBService class that runs all of its operations in the background while still getting live objects updates. So when i apply an addChangeListener, an exception is thrown:

java.lang.IllegalStateException: Your Realm is opened from a thread without a Looper. Async queries need a Handler to send results of your query

或者如果我使用 findAll() 而不是 findAllAsync():

or if i use findAll() instead of findAllAsync():

java.lang.IllegalStateException: You can't register a listener from a non-Looper thread or IntentService thread.

DBService 代码:

DBService code:

public Observable<List> getAll(Class clazz) {
    return Observable.defer(() -> {
        Realm realm = Realm.getDefaultInstance();
        return realm.where(clazz).findAll().asObservable()
                .map(o -> realm.copyFromRealm((RealmResults) o))
                .doOnUnsubscribe(() -> closeRealm(realm))
                .doOnTerminate(() -> closeRealm(realm));
    });
}

推荐答案

HandlerThread 完成这项工作.

HandlerThread does the job.

HandlerThread handlerThread = new HandlerThread("backgroundThread");
if (!handlerThread.isAlive())
    handlerThread.start();
AndroidSchedulers.from(handlerThread.getLooper());

这篇关于如何使用looper创建后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆