6

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]

Incinerator
  • 2,589
  • 3
  • 23
  • 30
coolsik
  • 61
  • 1
  • 4

3 Answers3

3

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.

Community
  • 1
  • 1
Phoenix Wang
  • 2,357
  • 1
  • 11
  • 17
  • 1
    Confirmed. You can read more [here](https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#subscriber) and [in this question](https://stackoverflow.com/questions/44640844/subscribewith-vs-subscribe-in-rxjava2android). – Incinerator Oct 12 '17 at 06:38
1

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.

Arnav Rao
  • 6,692
  • 2
  • 34
  • 31
  • That's correct, but unfortunately you don't always have access to implement or override the `Observer#onSubscribe` method. For example, my current problem is that I have `PublishSubject` as an `Observer`, and I cannot override its `#onSubscribe`. – Dmitriy Popov Jun 19 '19 at 10:03
0

Which version of RxJava do you use? With RxJava2 (io.reactivex.rxjava2):

public abstract class Observable<T> implements ObservableSource<T> {
  ...
  public final Disposable subscribe() {...}
  ...
}
Kevin Robatel
  • 8,025
  • 3
  • 44
  • 57
  • i use compile 'io.reactivex.rxjava2:rxandroid:2.0.1' on AndroidStudio – coolsik Jun 16 '17 at 07:19
  • https://github.com/ReactiveX/RxJava/blob/2.x/src/main/java/io/reactivex/Observable.java public final void subscribe(Observer super T> observer) { ... } – coolsik Jun 16 '17 at 07:19
  • Ho right! It's because `Observer` receive the `Disposable` in `onSubscribe(...)`. You have to use `Consumer` instead. – Kevin Robatel Jun 16 '17 at 07:48