Sobes.tech
Junior — Middle

Can you list and describe the types of Subject in RxJava?

sobes.tech AI

Answer from AI

In RxJava, a Subject is both an Observable and an Observer, meaning it can subscribe to other Observables and also act as a data source for subscribers.

Main types of Subject:

  1. PublishSubjectonly emits items after subscription. Subscribers do not receive past values.

  2. BehaviorSubject — immediately emits the last emitted item (or a default if none has been emitted yet) upon subscription, then all subsequent items.

  3. ReplaySubject — stores all emitted items and replays them to new subscribers, then continues to emit new items.

  4. AsyncSubject — only emits the last item to subscribers, and only after the Observable has completed.

Example of using BehaviorSubject:

BehaviorSubject<String> subject = BehaviorSubject.createDefault("Initial");

subject.subscribe(item -> System.out.println("Subscriber 1: " + item));

subject.onNext("First");

subject.subscribe(item -> System.out.println("Subscriber 2: " + item));

subject.onNext("Second");

Here, the second subscriber will immediately receive "First" — the last value at the moment of subscription.