Background operation using RxJava Android

What is Background operation?

Background processing in Android refers to the execution of tasks in different threads than the Main Thread, also known as UI Thread, where views are inflated and where the user interacts with our app.

Why background operation?

  • To avoid UI blockages by I/O events and prevent the famous “Application Not Responding” dialog. A freezing app means bad UX.
  • Some operations are not allowed ro run in the Main Thread, such as HTTP calls.
  • To improve performance.

 

We are commonly using asynctasks or intent service for background operations. But its quiet older methods. Now we can replace this all by RxJava. RxJava provides powerful threading and thread disposal on activity finish.

first, we need to add RXJava dependancy to our projects

//Rx
implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
//    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation('io.reactivex.rxjava2:rxandroid:2.0.2') {
    exclude group: 'io.reactivex.rxjava2', module: 'rxjava'
}


then create a disposable manger to add disposables and dispose when activity finish.

/**

 * DisposableManger is used to add rx java disposables and dispose on destroy
 * http://reactivex.io/RxJava/javadoc/io/reactivex/observers/DisposableObserver.html
 * http://reactivex.io/RxJava/javadoc/io/reactivex/disposables/Disposable.html

 */
public class DisposableManager {
    private static CompositeDisposable compositeDisposable;

    public static void add(Disposable disposable) {
        getCompositeDisposable().add(disposable);
    }

    public static void dispose() {
        getCompositeDisposable().dispose();
    }

    private static CompositeDisposable getCompositeDisposable() {
        if (compositeDisposable == null || compositeDisposable.isDisposed()) {
            compositeDisposable = new CompositeDisposable();
        }
        return compositeDisposable;
    }
    private DisposableManager() {
    }
}

 

then create a background thread for execution using RxJava

                                 final SessionDataJoined joined, boolean isFromSkillOnly) {
Disposable disposable = Observable.fromCallable(() -> {
   .....//WRITE CODE TO EXCECUTE IN BACKGROUND
   .....//
    return false;
}).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe((result) -> {
....//AFTER EXCECUTION COMPLETED YOU WILL GET THE RESULT RETURNED BY THE THREAD.
});

Add disposable to DisposableManager 

DisposableManager.add(disposable);

On activity finish

Dispose all disposables using

DisposableManager.dispose();

thats all for excecuting in background using rxjava

Categories: AndroidRxJava2

Leave a Reply

Your email address will not be published. Required fields are marked *

Social Media Auto Publish Powered By : XYZScripts.com