Learn about Subject in RxJava

Tram Ho

1, Definition

  • In this article I will introduce to you about 1 type of object in RxJava. Although not as common as the Observable or the Observer, it combines the combined strength of both. That is the Subject.
  • By the way, I have just returned to apply them and also to revise, in this article I will introduce to everyone about Subject types in RxJava. RxJava provides us with 4 types of Subjects:
    • Publish Subject.
    • Replay Subject.
    • Behavior Subject.
    • Async Subject.
  • Subjects are objects in RxJava that can interact with other components such as an Observable and an Observer. In short, it carries the power of both:
    • Because the subject is an observer, it can subscribe to one or more observables.
    • Because the Subject is Observable, it can pass items to the Observer by re-emmiting or emit new items.
  • Learning them through examples is an easy way to understand.
  • Admit:
    • Observable: teachers. Teachers teach students lessons.
    • Observer: student. Students will follow the teacher’s lessons.

2, Subject types

2.1 Publish Subject

  • If the student enters the classroom late, he only wants to listen at the time when he enters the classroom.

2.2 Replay Subject

  • If the student enters the classroom late, he wants to listen to the beginning of the lecture.

2.3 Async Subject

  • If the student enters the classroom at any one time, he just wants to hear the last thing.

2.4 Behavior Subject

  • If the student was late, he just wanted to hear the nearest thing.

3, Summary

  • Subject is less commonly used than Observable and Observer but is also very powerful and useful in many cases like Publish Subject used in Search.
  • Hopefully the brief article will help everyone understand Subject better.
Share the news now

Source : Viblo