javascript - Function in one branch always runs when use Observable.if -
i using observable.if determine action should dispatched.
the code below, since true, action1 dispatched, correct.
however, found myfunction() running didn't expect.
any explanation great. thanks
myfunction() { console.log('i did not expect run'); return 1; } export const myepic = (action$, store) => action$ .oftype('action') .mergemap(() => observable.if( () => true, observable.of({ type: 'action1' }), observable.of({ type: 'action2', payload: myfunction() }) ));
the problem myfunction needs evaluated when argument passed observable.of , result of observable.of passed observable.if argument, it's evaluated when observable.if called - not when observable.if receives next notification.
to solve problem, wrap in observable.defer call:
import 'rxjs/add/observable/defer'; // ... export const myepic = (action$, store) => action$ .oftype('action') .mergemap(() => observable.if( () => true, observable.of({ type: 'action1' }), observable.defer(() => observable.of({ type: 'action2', payload: myfunction() })) )); the call observable.of (and call myfunction) deferred until observable.if receives next notification.
Comments
Post a Comment