Observables - prevent onCompleted for array

54 views Asked by At

Let's say I have an array like so:

const values = [1,2,3];

I create an observable from this array like so:

const obs = Rx.Observable.from(values);

I subscribe like so:

obs.subscribe(
    function onNext(result){
        console.log('item =>', result);
    },
    function onError(e){
        console.error(e.stack || e);
    },
    function onCompleted(){
        console.log('observable is completed');
    }
);

the problem I am having is that if I push new items to the array like so:

setTimeout(function(){   
   values.push(4);
   values.push(5); 
   values.push(6);
}, 3000 );

these items (4,5,6) do not show up in the subscribe() callbacks!

So my question is, how can we create an observable array, that can "remain open" so that if items are pushed onto the array in the future, that the observer callbacks will fire?

I created a gist for this:

https://gist.github.com/ORESoftware/677ad0a3adf41c04a60829921ba4c4c4

and here is a fiddle:

https://jsfiddle.net/mcq40Lmg/

1

There are 1 answers

1
Asti On BEST ANSWER

If you are looking for the capability to push values through direct calls, you will need to use a Subject<T>.

const values = Rx.Observable.Subject();

setTimeout(function(){

   values.onNext(4);
   values.onNext(5); 
   values.onNext(6);

}, 3000 );

Using subjects for routine operations is not considered a good practice, and goes against the spirit of Rx. Subjects are, in essence, the mutable variables of Rx.

You can mostly get whatever functionality you want from the built-in operators, or create new ones which combine existing ones.