Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a background thread with a looper

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

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

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 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));
    });
}
like image 858
Zeyad Gasser Avatar asked Jan 20 '17 19:01

Zeyad Gasser


People also ask

How do I run a thread in the background?

thread. run() is going to execute the code in the thread's run method on the current thread. You want thread. start() to run thread in background.

What is a background thread?

Background threads are identical to foreground threads with one exception: a background thread does not keep the managed execution environment running. Once all foreground threads have been stopped in a managed process (where the .exe file is a managed assembly), the system stops all background threads and shuts down.

What's the best way to execute code in the background in a separate thread?

You can use a Handler to enqueue an action to be performed on a different thread. To specify the thread on which to run the action, construct the Handler using a Looper for the thread. A Looper is an object that runs the message loop for an associated thread.

What does Looper prepare do?

prepare. Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit() .


1 Answers

HandlerThread does the job.

HandlerThread handlerThread = new HandlerThread("backgroundThread");
if (!handlerThread.isAlive())
    handlerThread.start();
AndroidSchedulers.from(handlerThread.getLooper());
like image 97
Zeyad Gasser Avatar answered Oct 22 '22 15:10

Zeyad Gasser