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));
});
}
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.
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.
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.
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() .
HandlerThread does the job.
HandlerThread handlerThread = new HandlerThread("backgroundThread");
if (!handlerThread.isAlive())
handlerThread.start();
AndroidSchedulers.from(handlerThread.getLooper());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With