David Findlay
David Findlay

Reputation: 1356

RxJS Subject one off event

I understand that a Promise can only be used once and an Rxjs Subject can deliver multiple events.

If you are using rxjs in your application, is it good practice to use a Subject for something that a Promise could do?

In my service:

const addedItem: Subject = new Subject();
addedItem.next(res);
addedItem.complete();

My consumer just subscribes and the navigates when the message is received. Is this good practice?

Upvotes: 2

Views: 461

Answers (1)

Oles Savluk
Oles Savluk

Reputation: 4345

It depends, but in 90% of cases - No, you should not use Subject for "that".

The primary use case for them is to do multicasting(forwarding same notifications to multiple subscribers). But often, when people just start using ReactiveX, they tend to use them for imperatively pushing values (instead of just subscribing to them)

In your example you could:

  • use of(res) - this will create Observable with just 1 value
  • your consumer can directly subscribe to something that produces items

For more details read this blog posts by RxJS core team members:

Upvotes: 3

Related Questions