2

I'm creating a class for my app that keeps an internal BehaviorSubject. 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.

user3743222
  • 18,345
  • 5
  • 69
  • 75
mhelvens
  • 4,225
  • 4
  • 31
  • 55

1 Answers1

1

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.

Community
  • 1
  • 1
user3743222
  • 18,345
  • 5
  • 69
  • 75
  • Excellent! Yes, it seems the `.asObservable()` method [exists](http://reactivex.io/rxjs/file/es6/Subject.js.html#lineNumber98), and [has unit tests](http://reactivex.io/rxjs/test-file/spec-js/Subject-spec.js.html#lineNumber308), but is [not listed in the documentation](http://reactivex.io/rxjs/class/es6/Subject.js~Subject.html). Thanks! – mhelvens Jul 24 '16 at 00:17