2

I've been working with RxJS for a short while and I still cant get to grips with Subjects.

The documentation has the following

var source = Rx.Observable.from([1, 2, 3]);
var subject = new Rx.Subject();
var multicasted = source.multicast(subject);

But how is this different from?:

var source = Rx.Observable.from([1, 2, 3]);
var multicasted = source.share();

I often have to create classes that expose Observables but I don't want to expose Subjects as they have the next function. I don't want using classes to be able to push things into the pipeline. I currently do them like this:

var observer = null;
var sourceToBeExposed = Rx.Observable.create(ob => {
    observer = ob;
}).share();

// then later
if (observer != null)
   observer.next(newValue);

I'm struggling to work out why Subjects exist and what their main purpose is for. I'm sure I'm missing something important. Are there any good examples of Subjects someone can point me to?

Magpie
  • 6,983
  • 14
  • 51
  • 67
  • [`Observable#share()`](http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-share) doesn't return a `Subject` – Whymarrh Mar 10 '17 at 14:32
  • According to the documentation nor does multicast. http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-multicast – Magpie Mar 10 '17 at 14:45
  • Ok. What's the question? I don't understand. What does this have to do with `Subject`s? – Whymarrh Mar 10 '17 at 14:47
  • What is the purpose of Subjects? They seem to be Observables merged with Observers. What is the use case? In the mulicast example the Subject seems redundant. I'm trying to find a good example of their use. – Magpie Mar 10 '17 at 15:25
  • Yep cheers for the pointer – Magpie Mar 10 '17 at 16:21

1 Answers1

1

If you are looking for a way to not expose the .next in Typescript, you can return Subject.asObservable()

(Be aware though that this will only shield the source-access in Typescript, after transpiling to JavaScript one can still access the observable's source through the private attributes)

olsn
  • 16,644
  • 6
  • 59
  • 65