RxJS: How would I “manually” update an Observable?

前端 未结 2 1091
忘掉有多难
忘掉有多难 2021-01-29 18:39

I think I must be misunderstanding something fundamental, because in my mind this should be the most basic case for an observable, but for the life of my I can\'t figure out how

2条回答
  •  北海茫月
    2021-01-29 18:59

    I believe Observable.create() does not take an observer as callback param but an emitter. So if you want to add a new value to your Observable try this instead:

    var emitter;
    var observable = Rx.Observable.create(e => emitter = e);
    var observer = {
      next: function(next) {
        console.log(next);
      },
      error: function(error) {
        console.log(error);
      },
      complete: function() {
        console.log("done");
      }
    }
    observable.subscribe(observer);
    emitter.next('foo');
    emitter.next('bar');
    emitter.next('baz');
    emitter.complete();
    
    //console output
    //"foo"
    //"bar"
    //"baz"
    //"done"
    

    Yes Subject makes it easier, providing Observable and Observer in the same object, but it's not exactly the same, as Subject allows you to subscribe multiple observers to the same observable when an observable only send data to the last subscribed observer, so use it consciously. Here's a JsBin if you want to tinker with it.

提交回复
热议问题