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

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -