Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why rxjava Observable.subscribe(observer) return void?

When I'm using Observable.subscribe() normally returns Disposable.

But Observable.subscribe(Observer) returns void.

So I can't dispose to Observable.subscribe(Observer).

According to introtorx.com Observable.subscribe(Obeserver) returns Disposable.

Why are rx and rxjava different?

++++++++++++++

I use compile 'io.reactivex.rxjava2:rxandroid:2.0.1' in Android Studio.

github.com/ReactiveX/RxJava/blob/2.x/src/main/java/io/reactivex/Observable.java#L10831

public final void subscribe(Observer<? super T> observer) {
  ... 
}

[[1]: https://i.stack.imgur.com/0owg1.png][1]

[[2]: https://i.stack.imgur.com/7H4av.jpg][2]

like image 569
coolsik Avatar asked Jun 16 '17 07:06

coolsik


People also ask

What is Observable and observer in RxJava?

An Observable is like a speaker that emits a value. It does some work and emits some values. An Operator is like a translator which translates/modifies data from one form to another form. An Observer gets those values.

What is subscribe in RxJava?

RxJava implements several variants of subscribe . If you pass it no parameters, it will trigger a subscription to the underlying Observable, but will ignore its emissions and notifications. This will activate a cold Observable.

What is the difference between single and Observable in RxJava?

Single is an Observable which only emits one item or throws an error. Single emits only one value and applying some of the operator makes no sense. Like we don't want to take value and collect it to a list.

Is RxJava observer pattern?

RxJava is an open source library for Java and Android that helps you create reactive code. It's heavily inspired by functional programming. RxJava implements the Observer pattern with two main interfaces: Observable and Observer .


2 Answers

It's probably because of the Reactive Stream contract.

Reactive Stream README

public interface Publisher<T> {
    public void subscribe(Subscriber<? super T> s);
}

The interface of Publisher is defined return void. RxJava Flowable implements that interface. And RxJava Observable follow that contract as well.

So they provide a subscribeWith() to return you a Disposable instead of void. Or you can use those overload method which can give you back a disposable too ex: subscribe(consumer<T>,consumer<Throwable>,action)

PS: above its my guess. I'm not sure of it.

like image 200
Phoenix Wang Avatar answered Oct 24 '22 06:10

Phoenix Wang


In RxJava2, Disposable object is passed to Observer's onSubscribe call back method. You can get hold of Disposable object from onSubscribe call back method and use it to dispose the subscription at later point of time after subscribing the observer to observable.

like image 1
Arnav Rao Avatar answered Oct 24 '22 07:10

Arnav Rao