Slava Fomin II
Slava Fomin II

Reputation: 28671

Subscribe BehaviorSubject to Observable, but ignore errors and termination

I have a BehaviorSubject used by various classes in my application.

Sometimes, I want to publish to it a new data from server. I'm trying to do it this way:

const subject = new BehaviorSubject<Entity>(undefined);

loadDataFromServer().subscribe(subject);

The loadDataFromServer() function returns an Observable<Entity>, which emits one Entity on subscription and then finishes.

With such implementation, the BehaviorSubject will also terminate when the observable terminates. However, I would like to avoid this.

Of course, I can do:

loadDataFromServer().subscribe(entity => subject.next(entity));

However, I was wondering, are there other options to filter out error and termination events from the source observable? Or is it the optimal way to do this?

Upvotes: 1

Views: 215

Answers (1)

martin
martin

Reputation: 96999

I think what you're doing is fine and probably the easiest way to do it. However, if you want to do this with operators you could use materialize() and dematerialize(). This will first convert every emission into a special Notification object (all notifications will be wrapped and sent as next) where you can filter out everything but next notifications and then with dematerialize() convert them back to real emissions

loadDataFromServer()
  .pipe(
    materialize(),
    filter(notification => notification.kind === 'N'),
    dematerialize(),
  )
  .subscribe(subject);

Upvotes: 1

Related Questions