3

Is it possible for .subscribe to regularly listen to an array and its elements, and console.log new ones whenever they are being pushed on to the array?

Here are some code that i was experimenting with

let arr = [1, 2, 3, 4, 5]
let arraySource = from(arr);
//output: 1,2,3,4,5

let subscribe = arraySource.subscribe(val => console.log(val));

setTimeout(() => {
  arr.push(6);
},2000);

Thanks in advance

K N
  • 279
  • 5
  • 22

2 Answers2

0

The thing is that arr and arr$ aren't "connected". Once you subscribe to arr$, the elements originally in arr are emitted and then the observable completes. Further pushes to arr won't go through arr$:

const arr = [1,2,3];
const arr$ = from(arr);
arr$.subscribe(n => console.log(`n=${n}`));
arr.push(4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.1/rxjs.umd.min.js"></script>
<script>const {from} = rxjs;</script>

You should probably have a look at Subject and push data with next().

However if you don't care about arr and just want to use push() as a mean to push data through an observable, then there's a hacky way. I would personally not do that but I'll show this for demonstration purpose:

const arr = [];
const arr$ = fromEventPattern(handler => arr.push = handler);

arr$.subscribe(n => console.log(`n=${n}`));

let i = 0;
setInterval(() => arr.push(i++), 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.1/rxjs.umd.min.js"></script>
<script>const {fromEventPattern} = rxjs;</script>
customcommander
  • 17,580
  • 5
  • 58
  • 84
-1

I think you'd need to use observable.next() like so:

let arr = [1, 2, 3, 4, 5]
let arraySource = from(arr);
//output: 1,2,3,4,5

let subscribe = arraySource.subscribe(val => console.log(val));

setTimeout(() => {
  arraySource.next(6);
},2000);

And perhaps have another subscriber that updates array?

Varinder
  • 2,634
  • 1
  • 17
  • 20