Skip to content

Instantly share code, notes, and snippets.

@vespertilian
Created February 9, 2017 04:09
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save vespertilian/a541d24bae3729f9b6688b8eb08f12a0 to your computer and use it in GitHub Desktop.
Save vespertilian/a541d24bae3729f9b6688b8eb08f12a0 to your computer and use it in GitHub Desktop.
Two options for conditional ngrx effects
@Effect()
selectAndLoadStore$: Observable<Action> = this.actions$
.ofType(storeActions.SELECT_AND_LOAD_STORE)
.withLatestFrom(this.store.select(ngrx.storeState))
.map(([action, storeState]) => [action.payload, storeState])
.switchMap(([storeName, storeState]) => {
const existsInStore = Boolean(storeState.urlNameMap[storeName]);
return Observable.if(
() => existsInStore,
Observable.of(new storeActions.SetSelectedStore(storeName)),
this.storeService.getByUrlName(storeName)
.map(store => new storeActions.LoadSelectedStoreSuccess(store))
);
});
@Effect()
selectAndLoadStore$: Observable<Action> = this.actions$
.ofType(storeActions.SELECT_AND_LOAD_STORE)
.withLatestFrom(this.store.select(ngrx.storeState))
.map(([action, storeState]) => [action.payload, storeState])
.switchMap(([storeName, storeState]) => {
const existsInStore = Boolean(storeState.urlNameMap[storeName]);
let obs;
if (existsInStore) {
obs = Observable.of(new storeActions.SetSelectedStore(storeName));
} else {
obs = this.storeService.getByUrlName(storeName)
.map(store => new storeActions.LoadSelectedStoreSuccess(store));
}
return obs;
}); // @Effect()
@trevorchunestudy
Copy link

Brilliant! Thank you so much for this. Was stuck on how to make the syntax work.

@aire-con-gas
Copy link

I agree, this is great!

@victorcarvalhosp
Copy link

Oh man, thank you so much for this piece of code!

@truongluu
Copy link

Thank you very much, it works for me

@flashjpr
Copy link

Sweet mother of syntax! Thank you @vespertilian!

@aadiene
Copy link

aadiene commented Nov 5, 2021

Nicely done and very inspiring !
I adapted the code using rxjs iif because I want to just ignore the action if the condition is falsy.

        displayFirstTabByDefaultWhenLoadingTabs$ = createEffect(() => {
		return this.actions$.pipe(
			ofType(loadTabs),
			withLatestFrom(this.store.pipe(select(selectActiveTabIndex))),
			switchMap(([_loadTabsAction, activeTabIndex]) =>
				iif(
					() => !activeTabIndex && activeTabIndex !== 0,
					of(displayTab({ tabIndex: 0 }))
					// No result supplied, so it defaults to EMPTY
				)
			)
		);
	});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment