Should I call .doOnComplete() on the observable or subscribe with a new Observer<>?

Issue

I have a fairly simple logic I’m trying to implement. I have an audio tone that needs to complete playing before I start playing some sort of media content.

The audio tone I have is an observable. My current setup works, but I’m curious if I’m doing it the correct way.

This is what I have currently:

audioToneObservable
     .subscribeOn(Schedulers.io())
     .doOnComplete(() -> playMyFile())
     .subscribe();

Is this the correct way to achieve the flow I’m looking for? Or should my code look like this instead:

audioToneObservable
     .subscribeOn(Schedulers.io())
     .subscribe(new Observer<>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer integer) {
            }

            @Override
            public void onError(Throwable e) {
              playMyFile();
            }

            @Override
            public void onComplete() {
              playMyFile();
            }
          });

It works in both ways so I’m a bit confused if either of them are acceptable.

Solution

The Rx do* operators allow you to inject a side effect behavior into your sequence.

So, if you want to encapsulate the call of playMyFile() you can use doOnComplete(), also it will be called before onComplete().
But as I see you use onError() as well then in your case, it’s better to use doAfterTerminate() it will replace both (onComplete and onError).

Answered By – sergpetrov

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published