1

Reading the topic #2 from this article, it's clear that using create() properly can involve several issues, like:

  • Unregister callbacks when an Observable is unsubscribed (failing to do so can cause memory leaks)

  • Emit events using onNext or onCompleted only while a subscriber is still subscribed

  • Propagate errors upstream using onError

  • Handle backpressure

But seeing examples from the devs of RxJava2, like this one, where create() is used without any further checks or warnings, makes me wonder how deep are the issues with create()?

If I want Subject that can push a value at anytime, just like the one in that link:

Subject<Integer> subject = BehaviorSubject.<Integer>create().toSerialized();

Observable<Integer> observable = subject.observeOn(AndroidSchedulers.mainThread());

observable.subscribe(System.out::println);

subject.onNext(1)

Is it ok to use create() or is it dangerous as well? How to know when we need to protect create() emissions and when we don't have to?

Michel Feinstein
  • 13,416
  • 16
  • 91
  • 173
  • 2
    The aforementioned article is about 1.2.6, and in RxJava1 the `create` was renamed to `unsafeCreate`, and it is not even available in RxJava2 since its inception. The `Observable.create` in Rx2 is actually the `Observable.fromEmitter {` from Rx1, which was always safe to use. – EpicPandaForce Oct 17 '18 at 20:35
  • Interesting, I was looking into the source code of `SingleFromCallable` and since it takes care of most of the things in the article I thought it was still valid – Michel Feinstein Oct 17 '18 at 20:57

1 Answers1

2

Observable.create(OnSubscribe) is not the same create as with BehaviorSubject.create(). The latter was always safe as it created a final and pre-implemented BehaviorSubject, which is a hot Observable.

Observable.create(OnSubscribe) was used to setup a cold Observable from scratch and required the developer to implement the whole observable protocol correctly. It was error prone and late in the 1.x, the create(OnSubscribe) method was deprecated. Please read its javadoc for further details.

In RxJava 2, both types create methods are safe.

akarnokd
  • 69,132
  • 14
  • 157
  • 192