How to update UI from Android service using RxJava/RxAndroid

Amirhossein Kazemnejad picture Amirhossein Kazemnejad · Nov 20, 2015 · Viewed 8.6k times · Source

I have a Bound Service which responsible for downloading files and thus it knows the downloading status/progress. And the UI (Fragment or Activity) has to show/update download progress from the service.

Actually i think the common way is to use BroadcastReciever or a CallBack from Activity. But i heard somewhere about using RxJava (ReactiveX Programming) and mediator class (and Dagger to inject it into both service and activity) which is mentioned below.

So my question is how to handle RxJava with these bunch of stuff? Any Code Samples? Is there another efficient way than using intents?

Resource: More efficient way of updating UI from Service than intents? [ see the first answer update ]

Answer

Ujju picture Ujju · Apr 16, 2018

Required of RxJava/RxAndroid

1) OBSERVABLES 2) OBSERVERS 3) SUBSCRIBE

Plan where you need to place your 1, 2, 3,

OBSERVABLES go where the data is created, so In your case SERVICE

OBSERVERS go where the data needs to be consumed(or displayed), so that's your ACTIVITY

SUBSCRIBE goes anywhere where you have access to OBSERVABLE & OBSERVER, so lets use ACVITITY for that

Procedure and Code:

Firstly, Prepare your OBSERVABLE in service like this

class MyService extends Service {
    static PublishSubject<String> data = PublishSubject.create();

   @Override
   public void onStarCommand(Intent intent,int i, int j){
        # DO THIS ANYWHER WHERE YOU GENERATE DATA 
        data.onNext("Hello");
   }

   public static Observable<String> getObservable(){
      return data;
   }
}

Secondly, Prepare your OBSERVER(and OBSERVABLE) in Activity's onCreate

Observable<String> observable = MyService.getObservable();
Observer<String> observer = new Observer<String>() {
        @Override
        public void onCompleted() {
            Log.d(TAG, "onCompleted: ");
        }

        @Override
        public void onError(Throwable e) {
            Log.e(TAG, "onError: ",e);
        }

        @Override
        public void onNext(String text) {
            Log.d(TAG, "DATA reveived here: "+text);
        }
    };

Lastly Link both OBSERVER and OBSERVABLE in Activity, else Observable will not respond, use this again in onCreate

observable.subscribe(observer);

DONE, Now when even the data is triggered from Service using onNext(), the data arrives in Activity