0

I have a single HTML element :

 <ul id="animals"></ul>

And this code which observe an array and append its element as HTML elements :

  const zooAnimals = ['anteater', 'bear', 'cheetah', 'donkey'];

  const observable = Rx.Observable.from(zooAnimals);

  const subscriber = observable

    .subscribe(
      onNext,
      function onError(err) {
        console.log('Error: ' + err);
      },
      function onCompleted() {
        console.log('no more animals!');
      }
    );

  function onNext(animal) {
    const list = document.querySelector('#animals');
    console.log('list', list)
    const li = document.createElement('li');
    li.innerHTML = animal;
    list.appendChild(li);
  }

So now the #animals element is filled with 4 ULs.

But Now I want to add another element via setTimeout

So I add :

setTimeout(function (){
  zooAnimals.push('dddddd');
},4000);

But nothing happens.

Question

What am I missing here and how can I mek this code work if some other soure appends items to the array.

plunker :

https://plnkr.co/edit/xzyjCOR8lKl3tc70kzC9?p=info

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

1

That is not how Observables work, in RxJS everything is a stream and to emit new data you need to use the RxJS-api - there are many ways to achieve this for your issue, one of those would be to use a Subject - which is basically a combination of Observer and Observable, meaning that you can emit data on it and at the same time subscribe to it:

  const zooAnimals = ['anteater', 'bear', 'cheetah', 'donkey'];
  const subject = new Rx.Subject();

  const subscriber = subject
    .subscribe(
      onNext,
      function onError(err) {
        console.log('Error: ' + err);
      },
      function onCompleted() {
        console.log('no more animals!');
      }
    );

  function onNext(animal) {
    const list = document.querySelector('#animals');
    console.log('list', list)
    const li = document.createElement('li');
    li.innerHTML = animal;
    list.appendChild(li);
  }

  zooAnimals.forEach(animal => subject.onNext(animal));
  setTimeout(() => subject.onNext("giraffe"), 100);

I've updated your plunker as well: https://plnkr.co/edit/bx9NtRT0n5HuZQSCcvkH?p=preview


As a sidenote: If you are now starting to get into RxJS I would suggest you to use RxJS5, which is the latest version of the library.

olsn
  • 16,644
  • 6
  • 59
  • 65
  • Can you please have a look here ? Didn't get a satisfying answer there http://stackoverflow.com/q/43419163/859154 – Royi Namir Apr 15 '17 at 22:16