mhelvens mhelvens - 10 months ago 58
Javascript Question

RxJS 5: Can I create a `BehaviorObservable`?

I'm creating a class for my app that keeps an internal

. Is there a way I can expose a corresponding '
BehaviorObservable
', which pipes through the values of the subject, but only has the 'read-only' stuff of the
Observable
interface? The
.next()
,
.error()
and
.complete()
methods should only be available internally.

It's not just a matter (I believe) of using
Observable.create()
to pipe the subject's values through. Users of my API should
.subscribe()
to the exposed observable, and then immediately get a callback for the stored current value.

I may be able to hack something together, but I'm sure I'm just missing something that RxJS can already do.

Answer Source

Are you by any chance looking for the .asObservable() method - which existed in Rxjs v4. Don't know if that is still the case in Rxjs v5 though.

According to this, the method should have been included in release 5.0.0-beta.2. Also I quote here their work-around if the functionality is not there :

You can get the same functionality by creating an observable with the private subject's subscribe function:

> const subj = new rx.Subject();
> const exposed = new rx.Observable(fn => subj.subscribe(fn));

For more details about subjects' semantics, you can have a look here.