RxJava Relay Against Objects

I am trying to understand the purpose of this library from Jake Warton: https://github.com/JakeWharton/RxRelay

Basically: the subject, except when it is not possible to call onComplete or onError. Subjects are in a state of damage and damage: when they receive onComplete or onError, they can no longer be used to move data.

I realized that this is the right use case, but the above seems easy to achieve by simply using existing items.

1. Do not forward errors / completions messages to the topic:

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

2. Do not open the topic, make sure that the signature of your method returns the observable.

fun(): Observable<> { return subject }

Obviously, I am missing something here, and I am very interested in 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 } 
+9
source share
2 answers

subscribe has overloads and, as a rule, people get used to subscribe(Consumer) overloads. Then they use objects, and suddenly onComplete also called. RxRelay saves the user from himself, who does not think about the difference between subscribe(Consumer) and subscribe(Observer) .

  • Do not forward error / termination events to the topic:

Indeed, but, based on our experience with beginners, they often don’t think about it or even don’t know about the methods available.

  1. Do not expose the object so that your method signature returns the observable instead.

If you need a way to post items to a topic, this will not work. The goal is to use the subject to multicast, sometimes from another Observable . If you are in full control of emissions through Subject , you must be honest in not calling onComplete and not allowing anything else to be done.

+5
source

If you use Subjects, executing subjects.getValue will always throw a zero security error. So you have to put "? Or !!" everywhere in your code, even if you know that it will not be nullable.

 public T getValue() { Object o = value.get(); if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { return null; } return NotificationLite.getValue(o); } 
0
source

Source: https://habr.com/ru/post/1270607/


All Articles