Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BehaviorSubject vs PublishSubject

I'm trying to get my head around the golden rule (if any) about:

When to use BehaviorSubject ?

and

When to use PublishSubject ?

The difference between them is very clear

There are many kinds of subjects. For this specific requirement, a PublishSubject works well because we wish to continue the sequence from where it left off. So assuming events 1,2,3 were emitted in (B), after (A) connects back we only want to see 4, 5, 6. If we used a ReplaySubject we would see [1, 2, 3], 4, 5, 6; or if we used a BehaviorSubject we would see 3, 4, 5, 6 etc. (source : How to think about Subjects in RxJava (Part 1))

I have seen that Subject's are used in two contexts (at least), UI context and listener context.

  • UI context (MVVM as example)

For example here a BehaviorSubject is used, and it's clear why they use Subject and not Observable but I have changed the BehaviorSubject to PublishSubject but the app behavior still the same.

  • Listener context

Why they make project field a BehaviorSubject and not PublishSubject ?

like image 965
Cool Avatar asked Apr 25 '18 10:04

Cool


People also ask

What is the difference between PublishSubject and BehaviorSubject?

PublishSubject : Starts empty and only emits new elements to subscribers. BehaviorSubject : Starts with an initial value and replays it or the latest element to new subscribers. ReplaySubject : Initialized with a buffer size and will maintain a buffer of elements up to that size and replay it to new subscribers.

What is PublishSubject?

PublishSubject emits items to currently subscribed Observers and terminal events to current or late Observers.

What is PublishSubject RxSwift?

RxSwift: Publish SubjectUseful when you want subscribers to be notified of new events from the point at which they subscribed until they either unsubscribe or termination ( . completed / . error ). Will emit stop event to new subscribers and no longer emit .

What is reactive programming subject?

1. What is a Subject? As mentioned, a Subject is nothing more like an observable with a few more characteristics. An observable is by definition an invokable collection that emits data once subscribed. Meanwhile, a Subject is where we control the state of “when to emit data” to multiple subscribers.


1 Answers

The main difference between PublishSubject and BehaviorSubject is that the latter one remembers the last emitted item. Because of that BehaviorSubject is really useful when you want to emit states

Why they make project field a BehaviorSubject and not PublishSubject ?

Probably because they want to be able to retrieve the last emitted project with this method:

@Override public @NonNull Observable<Project> project() {   return this.project; } 
like image 145
Dmitry Avatar answered Oct 05 '22 21:10

Dmitry