Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava Relay vs Subjects

Tags:

rx-java2

I'm trying to understand the purpose of this library by Jake Warthon: https://github.com/JakeWharton/RxRelay

Basically: A Subject except without the ability to call onComplete or onError. Subjects are stateful in a damaging way: when they receive an onComplete or onError they no longer become usable for moving data.

I get idea, it's a valid use case, but the above seems easy to achieve just using the existing subjects.

1. Don't forward errors/completions events to the subject:

`observable.subscribe({ subject.onNext(it) }, { log error / throw exception },{ ... })`

2. Don't expose the subject, make your method signature return an observable instead.

fun(): Observable<> { return subject }

I'm obviously missing something here and I'm very curios on what it is!

class MyPublishRelay<I> : Consumer<I> {

    private val subject: Subject<I> = PublishSubject.create<I>()

    override fun accept(intent: I) = subject.onNext(intent)

    fun subscribe(): Disposable = subject.subscribe()
    fun subscribe(c: Consumer<in I>): Disposable = subject.subscribe(c)
    //.. OTHER SUBSCRIBE OVERLOADS
}
like image 211
frankelot Avatar asked Aug 05 '17 06:08

frankelot


1 Answers

subscribe has overloads and, usually, people get used to the subscribe(Consumer) overload. Then they use subjects and suddenly onComplete is also invoked. RxRelay saves the user from themselves who don't think about the difference between subscribe(Consumer) and subscribe(Observer).

  1. Don't forward errors/completions events to the subject:

Indeed, but based on our experience with beginners, they often don't think about this or even know about the available methods to consider.

  1. Don't expose the subject, make your method signature return an observable instead.

If you need a way to send items into the subject, this doesn't work. The purpose is to use the subject to perform item multicasting, sometimes from another Observable. If you are in full control of the emissions through the Subject, you should have the decency of not calling onComplete and not letting anything else do it either.

like image 75
akarnokd Avatar answered Oct 13 '22 14:10

akarnokd