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

前端 未结 2 1131
忘掉有多难
忘掉有多难 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 19:19

    In RX, Observer and Observable are distinct entities. An observer subscribes to an Observable. An Observable emits items to its observers by calling the observers' methods. If you need to call the observer methods outside the scope of Observable.create() you can use a Subject, which is a proxy that acts as an observer and Observable at the same time.

    You can do like this:

    var eventStream = new Rx.Subject();
    
    var subscription = eventStream.subscribe(
       function (x) {
            console.log('Next: ' + x);
        },
        function (err) {
            console.log('Error: ' + err);
        },
        function () {
            console.log('Completed');
        });
    
    var my_function = function() {
      eventStream.next('foo'); 
    }
    

    You can find more information about subjects here:

    • https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/subject.md
    • http://reactivex.io/documentation/subject.html

提交回复
热议问题