RxJS and React setState - executing delay until subscribe function

RxJS has a great function, fromCallback , which takes a function whose last parameter is a callback and returns Observable

. And I want to combine this with a React function setState

so that I can do something similar:

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

      

so any operations bound to setState are guaranteed after the state has been set and, most importantly, that setState

it is not called until there is an active caller.

What I noticed is that even without subscribing setState

it gets called correctly as defined and setting the state of my component. Therefore, if I have:

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

      

the function is setState

immediately called, but the observer it produces does not dispatch the next one until the subscriber appears. I want the function to only call when there is a subscriber.

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

+2


source to share


1 answer


fromCallback

returns a function that, when executed, returns the observed value. The observable is where the asynchronous result of the function call will flow.

To delay execution of a function, you can use .defer

. For example:



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

      

A question whose answers used the same method was asked here and here

+3


source







All Articles