1
votes

I am struggling with RxJS. Some questions about Observable

  1. Does Observable empty the data array after onCompleted is called?
  2. when I chain two subscribe() method together I got error "subscribe does not exist in type Subscription". Why is that?

    someObs.map(...).subscribe(...).subscribe(...)

  3. Is there a way to check an observable data array count without subscribing?

  4. If Observable clears the data items after emitting them is there a way to refill new data items into the same observable instance without creating a new one? if yes, how?

1
Not sure about the others, but 2 doesn't work because the return of #subscribe() is of type Subscription, which does not have a method called #subscribe(). In order for that to work, #subscribe() would have to return the Observable again, which wouldn't really make sense. You should move the .subscribe() calls to their own lines, instead of chaining both of them. Oh and for #4, you could use a Subject.dvlsg

1 Answers

1
votes
  1. No. RxJS is a close cousin of Functional Programming, which means that mutation is generally a big no-no. The whole point of streaming data is to avoid state mutation, which is in many ways the source of many troubles in today's applications.

All Observables do is wrap various data source types so that they emit events through a common interface. Hence Rx.Observable.fromArray and Rx.Observable.fromPromise both produce Observables with the same semantics, the only difference being the number of events and when those events are produced.

  1. Observables are lazy, all the fancy method chaining doesn't do anything until the Observable is finally subscribed to. So that subscribe is really like saying "execute" or "go", it will allow events to begin moving through the Observable.

  2. Not sure what you mean by "Observable data array", see point 1. If you pass an array to an Observable then you should be able to check the size of that

  3. It doesn't, but yes you can in a sense "refill" an Observable based on an Array by simply resubscribing to it, that will begin the process of sending the events again. As dvlsg mentioned you could also use a Subject to explicitly push events to an Observer, but in 99% of the cases its use can and should be avoided because it is being used as a crutch to avoid having to actually be reactive

i.e.

var source = Rx.Observable.fromArray([1, 2, 3, 4]);

//First subscription, prints all of the events from array
source.subscribe(x => console.log(x));

//Second subscription, prints all the events *again* because
//this is a new subscription occurrence
source.subscribe(y => console.log(y));