Using Consumer interface of Reactivex

11.2k Views Asked by At

I'm new to ReactiveX. I was learning it from reading source-code. Everything was so clear but suddenly I got this word named "Consumer" which was an Interface. It was used in place of Observer.

Can someone let me know what it exactly does?

I followed several links but they just all said just one statement Consumer is a functional interface (callback) that accepts a single value.

I want to know the exact working of it.

  1. What is it?
  2. Why do we need it?
  3. How do you use it?
  4. Does it take the place of Observer? If YES, how and why?
3

There are 3 best solutions below

1
On BEST ANSWER

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

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()
                );
0
On

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
);
0
On

In my humble opinion, consumer is for reverse / bi-directional streams.

For example, your data source emits a "Y" of complex time-dependent operations executed from a parameter "X" in the form of a "hot" flowable (HF).

Suppose the parameter X is emitted through a "hot" observable (HO), so, your data source can be a consumer that subscribes to the "HO" and emits the result of the complex operations through the HF.

In this case, you have the bi-directional stream and you used the consumer to push the date provided through the HO in the data source.

I am not sure if my answer is really correct... rx is a little bit complex :B