0

I'm not quite understanding the difference between using an observable's doOnNext/doOnSubscribe/doOnComplete versus passing in an observer through the observable's subscribe function. These two seem to do the same thing to me. Can someone give me a use case where I would use one over the other?

                                Observable.interval(1, TimeUnit.SECONDS)
                                    .take(30)
                                    .map(v -> v + 1) 
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .doOnNext(new Consumer<Long>() {
                                        @Override
                                        public void accept(Long aLong) throws Throwable {
                                            // update UI 
                                        }
                                    })

                            Observable.interval(1, TimeUnit.SECONDS)
                                    .take(30)
                                    .map(v -> v + 1)
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Observer<Long>() {
                                        @Override
                                        public void onSubscribe(@NonNull Disposable d) {
                                            
                                        }

                                        @Override
                                        public void onNext(@NonNull Long aLong) {
                                              // update ui
                                        }

                                        @Override
                                        public void onError(@NonNull Throwable e) {

                                        }

                                        @Override
                                        public void onComplete() {

                                        }
                                    })
dman224
  • 7
  • 4

1 Answers1

0

The doOnNext operator allows you to perform a side effect action, such as logging or additional processing, for each emitted item without modifying or consuming the item itself.

The subscribe method is used to consume the items and define the behavior of the Observer. This is typically the final step in the observable chain.

Observable.range(1, 5)
    .doOnNext(number -> System.out.println("Current number: " + number))//logging
    .map{number -> number*2}
    .subscribe(System.out::println); //will print [2,4,6,8,10]
Avik Chowdhury
  • 171
  • 1
  • 1
  • 7