Learn about Subject in RxJava-Publish, Replay, Behavior Va Async Subject

Tram Ho

In this article we will learn about Subject in RxJava

  • Publish Subject
  • Subject replay
  • Behavior Subject
  • Async Subject

Before going into the details in the article, I can give you a very good example of rxjava 2 by author amitshekhariitbhu , you can refer to amitshekhariitbhu / RxJava2-Android-Samples

So what is Subject?

Một Chủ đề là một sắp xếp của câu lệnh hay proxy mà sẵn sàng trong một số thực hiện của ReactiveX mà việc hiện thời là một Observer và như một Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through it observes by re-emitting them, and it can also emit new items.

I think the best way to learn is through examples

Observable : suppose that a Professor (a professor) is a observable. The professor teaches a few topics (topics). Observer : suppose that a student (student) is a observer. Student observes the topic being taught by the professor.

Publish Subject

It emits all subsequent entries of source observable at the time of registration. If a student comes in late for the class, then the student just wants to listen at the time that student comes into class. So publish will be best in this case.

Look at the example below:

Subject replay

It emits all items of the Observable source, regardless of when subscriber registers. Here, if a student goes to the late class, the student wants to hear lessons from the beginning. So here will use Replay to get this.

Look at the example below:

Behavior Subject

It emits the most recently released items and all subsequent entries of source observable when an observer registers to it.

Here if a student comes to class late, student wants to hear everything closest (not everything at the beginning) being taught by the professor to the student which is the idea of ​​context. So here is Behavior.

Async Subject

It only emits the last value of the Observable source (only one last value) only after the Observable source is complete. Here, if student enters the class any time and student just wants to listen only. on a final topic (only one last topic) is being taught, after the class ends. So here will use Async

References:

https://blog.mindorks.com/understanding-rxjava-subject-publish-replay-behavior-and-async-subject-224d663d452f

http://reactivex.io/documentation/subject.html

Share the news now

Source : Viblo