RxJS和React的setState - 延迟函数执行直到订阅 [英] RxJS and React's setState - delay function execution until subscription

查看:383
本文介绍了RxJS和React的setState - 延迟函数执行直到订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

RxJS有一个很棒的功能, fromCallback ,它接受一个函数,其最后一个参数是一个回调并返回一个 Observable 。我想将它与React的 setState 函数结合起来,这样我就可以做类似的事情:

RxJS has a nifty function, fromCallback that takes a function whose last parameter is a callback and returns an Observable. And I want to combine that with React's setState function so that I can do something analogous to:

const setState = Rx.Observable.fromCallback(this.setState);
setState({ myState: 'Hi there!' }).concat(....)

以便在设置状态后保证链接到setState的任何操作都会发生,最重要的是,在有活动订阅者之前不会调用 setState

so that any operations chained to setState are guaranteed to happen after the state has been set and, most importantly, that setState isn't invoked until there's an active subscriber.

我注意到的是,即使没有订阅, setState 也会被正确调用,因为它已经定义并设置了我的组件的状态。所以如果我有:

What I noticed though is that even without a subscribe, setState is being called right as it's defined and setting the state of my component. So if I have:

networkSignal.flatMap((x) => {
    return setState({ myState: 'test' });
});

立即调用函数 setState 但是观察者,生产者在订阅者之前不会发送下一个。我想要的是该函数只在订阅者时调用。

the function setState is immediately invoked but the observer it producers won't send a next until there's a subscriber. What I want is for the function to only invoke when there's a subscriber.

查看源代码,您可以看到RxJS返回一个函数,该函数在执行时会创建一个可观察但是立即调用函数 - 回调参数。

Looking into the source you can see that RxJS returns a function that when executed, creates an observable but immediately invokes the function - the callback argument.

推荐答案

fromCallback 返回一个函数,该函数在执行时返回一个observable 。该可观察量是函数调用的异步结果将流动的位置。

fromCallback returns a function which, when executed, returns an observable. That observable is where the asynchronous result(s) of the function call will flow.

要延迟执行该功能,您可以使用 .defer 。例如:

To delay the execution of the function, you can make use of .defer. For instance:

const setState = Rx.Observable.fromCallback(this.setState);
const deferred$ = Rx.Observable.defer(function (){return setState({ myState: 'Hi there!' }).concat(....)});
// Later on
deferred$.subscribe(...)

回答使用相同技术的问题被提出这里这里

Question whose answers used the same technique were asked here and here

这篇关于RxJS和React的setState - 延迟函数执行直到订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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