Using Consumer interface of Reactivex

Consumer is a simple Java interface that accepts variable of type T. Like you said it is used for callbacks.

Example:

import io.reactivex.functions.Consumer;

Flowable.just("Hello world").subscribe(new Consumer<String>() {
      @Override public void accept(String s) {
          System.out.println(s);
      }
  });

Why does it work? How can we use a Consumer instead of an Observer?

RxJava simply creates an Observer, passes the Consumer to it an it gets called in onNext

Update

  • You call Observable.subscribe(Consumer onNext)

  • Observable.subscribe(Consumer onNext, Consumer onError, Action onComplete, Consumer onSubscribe) gets called

  • LambdaObserver is created

LambdaObserver is a kind of observer that is created out of four functional interfaces and uses them as callbacks. It's mostly for using java 8 lambda expressions. It looks like this:

Observable.just(new Object())
                .subscribe(
                        o -> processOnNext(o),
                        throwable -> processError(throwable),
                        () -> processCompletion(),
                        disposable -> processSubscription()
                );

A Consumer consumes the values you receive when subscribing. It's like a Subscriber who passes the emitted data as callback.

The Consumer is a simple Interface which has a callback for a generic Type and is needed to receive the emitted items by the Observable.

Take care that if you only have a Consumer that you don't catch errors and you may get problems by debugging.

You can solve that by using another Consumer as second parameter which receives a Throwable.

Flowable.just("Hello world")
  .subscribe(
            emittedData -> System.out.println(emittedData), // onNext
            throwable -> throwable.printStackTrace() // onError
);