RxJS:我将如何“手动"?更新一个 Observable? [英] RxJS: How would I "manually" update an Observable?

查看:44
本文介绍了RxJS:我将如何“手动"?更新一个 Observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我一定是误解了一些基本的东西,因为在我看来,这应该是 observable 最基本的情况,但在我的一生中,我无法从文档中弄清楚如何做到这一点.

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 to do it from the docs.

基本上,我希望能够做到这一点:

Basically, I want to be able to do this:

// create a dummy observable, which I would update manually
var eventObservable = rx.Observable.create(function(observer){});
var observer = eventObservable.subscribe(
   function(x){
     console.log('next: ' + x);
   }
...
var my_function = function(){
  eventObservable.push('foo'); 
  //'push' adds an event to the datastream, the observer gets it and prints 
  // next: foo
}

但是我一直没能找到像push这样的方法.我正在使用它作为点击处理程序,我知道他们有 Observable.fromEvent ,但我正在尝试将它与 React 一起使用,我宁愿能够简单地更新数据流在回调中,而不是使用完全不同的事件处理系统.所以基本上我想要这个:

But I have not been able to find a method like push. I'm using this for a click handler, and I know they have Observable.fromEvent for that, but I'm trying to use it with React and I'd rather be able to simply update the datastream in a callback, instead of using a completely different event handling system. So basically I want this:

$( "#target" ).click(function(e) {
  eventObservable.push(e.target.text()); 
});

我得到的最接近的是使用 observer.onNext('foo'),但这似乎并没有真正起作用,而是调用了观察者,这似乎不正确.观察者应该是对数据流做出反应的东西,而不是改变它,对吗?

The closest I got was using observer.onNext('foo'), but that didn't seem to actually work and that's called on the observer, which doesn't seem right. The observer should be the thing reacting to the data stream, not changing it, right?

我只是不理解观察者/可观察者的关系吗?

Do I just not understand the observer/observable relationship?

推荐答案

在 RX 中,Observer 和 Observable 是不同的实体.观察者订阅一个 Observable.Observable 通过调用观察者的方法向其观察者发出项目.如果您需要调用 Observable.create() 范围之外的观察者方法,您可以使用 Subject,它是一个代理,同时充当观察者和 Observable.

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.

你可以这样做:

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:

这篇关于RxJS:我将如何“手动"?更新一个 Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆