RxJS and React's setState - delay function execution until subscription

霸气de小男生 提交于 2019-12-10 11:14:52

问题


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(....)

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.

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' });
});

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.

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.


回答1:


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

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



来源:https://stackoverflow.com/questions/34866762/rxjs-and-reacts-setstate-delay-function-execution-until-subscription

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!