How to transform combineLatest to switchMap? - rxjs

I have to observables, i know there is a way to transform combineLatest to switchMap but i dont get it
combineLatest([
faviconServiceOutgoingEvents.ready.listen().pipe(mapTo(true), startWith(false)),
this.brandService.brandName$,
]).subscribe(([isServiceReady, brandName]) => {
if (isServiceReady) {
faviconServiceIncomingEvents.changeIcon.send(brandName);
}
});

solution was near
faviconServiceOutgoingEvents.ready
.listen()
.pipe(
switchMap(() => {
return this.brandService.brandName$;
}),
)
.subscribe(brandName => faviconServiceIncomingEvents.changeIcon.send(brandName));

Related

How to dispatch multiple actions from an effect in ngrx conditionally

I am a back-end developer starting with front-end development for a project I am working on. The front-end uses Angular7 and NgRx. I have studied a lot in the last 4 days, but here is something I am stuck with and would appreciate your help.
I learnt that we can dispatch multiple actions from an effect in NgRx by returning an Observable array having multiple actions. I want to dispatch one of the action in the array based on a condition.
My code looks something like this
#Effect()
something$: Observable<Action> = this.actions$.pipe(
ofType(ActionType),
switchMap.(action: any) => {
return service.call(action.payload)
.pipe(
switchMap((data: ReturnType) => [
new Action1(),
new Action2(),
]),
catchError(error handling)
);
}),
);
and I want to achieve something like this
#Effect()
something$: Observable<Action> = this.actions$.pipe(
ofType(ActionType),
switchMap.(action: any) => {
return service.call(action.payload)
.pipe(
switchMap((data: ReturnType) => [
if(condition)
new Action1()
else
new Action1.1() ,
new Action2(),
]),
catchError(error handling)
);
}),
);
I think its my lack of knowledge of RxJs, which is preventing me to implement the condition.
You can dispatch multiple actions or specific actions by letting conditional ifs determine what iterable to return
I recommend you read: https://www.learnrxjs.io/operators/transformation/switchmap.html
#Effect()
something$: Observable<Action> = this.actions$.pipe(
ofType(ActionType),
switchMap(action: any) => {
return service.call(action.payload)
.pipe(
switchMap((data: ReturnType) => {
let actionsToDispatch = [];
if(condition) {
actionsToDispatch.push(new SomeAction())
} else {
actionsToDispatch.push(new SomeOtherAction())
}
return actionsToDispatch
}),
catchError(error handling)
);
}),
);
To dispatch multiple actions you can pass the action array as shown below:
#Effect()
getTodos$ = this.actions$.ofType(todoActions.LOAD_TODOS).pipe(
switchMap(() => {
return this.todoService
.getTodos()
.pipe(
switchMap(todos => [
new todoActions.LoadTodosSuccess(todos),
new todoActions.ShowAnimation()
]),
catchError(error => of(new todoActions.LoadTodosFail(error)))
);
})
);
To dispatch actions conditionally you can wrap the actions in if/else as shown below:
#Effect()
getTodos$ = this.actions$.ofType(todoActions.LOAD_TODOS).pipe(
switchMap(() => {
return this.todoService
.getTodos()
.pipe(
switchMap(todos => {
if(true) {
return new todoActions.LoadTodosSuccess(todos),
} else {
return new todoActions.ShowAnimation()
}),
catchError(error => of(new todoActions.LoadTodosFail(error)))
);
})
);
Hope that helps!

RxJS: Make sure "tap" is fired even after unsubscribe

How can I make sure the tap operator is called even if a subscription is unsubscribed? Imagine the following:
function doUpdate() {
return this.http.post('somewhere', {})
.pipe(
tap(res => console.log(res))
)
}
const sub = doUpdate().subscribe(res => /* do something with res */);
setTimeout(() => sub.unsubscribe(), 1000)
In this case, I just want to prevent the subscribe action from being executed, yet I want to make sure the console log is fired, even if the request took longer than 1000 milliseconds to execute (and in this particular case, I don't even want the POST to be cancelled either).
use finalize() operator, although that will also get called when observable is completed
function doUpdate() {
return this.http.post('somewhere', {})
.pipe(
finalize(() => console.log(res))
)
}
some code to demonstrate the idea:
https://stackblitz.com/edit/rxjs-playground-test-m9ujv9
In Rxjs 7.4 tap now has three more subscribe handlers, so you can use it to get notified on subscribe, unsubscribe and finalize:
https://github.com/ReactiveX/rxjs/commit/eb26cbc4488c9953cdde565b598b1dbdeeeee9ea#diff-93cd3ac7329d72ed4ded62c6cbae17b6bdceb643fa7c1faa6f389729773364cc
So you can do:
const subscription = subject
.pipe(
tap({
subscribe: () => results.push('subscribe'),
next: (value) => results.push(`next ${value}`),
error: (err) => results.push(`error: ${err.message}`),
complete: () => results.push('complete'),
unsubscribe: () => results.push('unsubscribe'),
finalize: () => results.push('finalize'),
})
)
.subscribe();
Unsubscribing from a http request will definitely cancel the request, you could try shareReplay
function doUpdate() {
return this.http.post('somewhere', {})
.pipe(
tap(res => console.log(res)),
shareReplay()
)
}
and if that doesn't work the passing the result into a subject
function doUpdate() {
const subject = new Subject();
this.http.post('somewhere', {})
.pipe(
tap(res => console.log(res))
).subscribe(subject);
return subject;
}

How to correctly handle errors in this effect?

I've written the Effect below to make requests for each item in the array, and when one fails, the error isn't handled and the observable stream completes resulting actions not triggering effects any further.
Effect:
#Effect() myEffect$ = this.actions$.pipe(
ofType<myAction>(myActionTypes.myAction),
mergeMapTo(this.store.select(getAnArray)),
exhaustMap((request: any[]) => {
return zip(...request.map(item => {
return this.myService.myFunction(item).pipe(
map(response => {
return this.store.dispatch(new MyActionSuccess(response))
}),
catchError(error => {
return Observable.of(new MyActionFailure(error));
})
)
}))
})
How do I handle the error in this case?

RxJS to return a new object with an array payload

I am trying to get my NgRX effect to return an action object. The action object indicates a "success", and needs to return all retrieved institutions as part of the payload. How do I do this? Please note that the block inside of the mergeMap does not work. I need to return all the retrieved institutions as part of a payload after retrieving them.
#Effect()
getInstitutions$ = this.actions$
.ofType(institutionActions.InstitutionActionTypes.GetInstitutions)
.pipe(
switchMap(() => {
const institutions = this.getInstitutions();
console.log(institutions);
return this.getInstitutions();
}),
mergeMap((institutions: Institution[]) => {
// return institutions;
return {
type: institutionActions.InstitutionActionTypes.GetInstitutionsSuccess,
payload: institutions
};
})
);
You have to operate on this.getInstitutions() as in:
#Effect()
getInstitutions$ = this.actions$
.ofType(institutionActions.InstitutionActionTypes.GetInstitutions)
.pipe(
switchMap(() => {
return this.getInstitutions().pipe(
map(institutions => ({
type: institutionActions.InstitutionActionTypes.GetInstitutionsSuccess,
payload: institutions
})),
catchError(_ => ...) //don't forget to handle errors
)
})
);
As a side note, I would encourage you to use action creators, instead of creating action objects "all over the place" - Let’s have a chat about Actions and Action Creators within NgRx
How about using "map" instaed mergeMap. Can you try following?
#Effect()
getInstitutions$ = this.actions$
.ofType(institutionActions.InstitutionActionTypes.GetInstitutions)
.pipe(
switchMap(() => {
const institutions = this.getInstitutions();
console.log(institutions);
return this.getInstitutions();
}),
map((institutions: Institution[]) => {
// return institutions;
return {
type: institutionActions.InstitutionActionTypes.GetInstitutionsSuccess,
payload: institutions
};
})
);
Hope that helps!

Rxjs conditional switchMap based on a condition

I have a situation like the following:
myObservable1.pipe(
switchMap((result1: MyObservable1) => {
if (condition) {
return myObservable2;
} else {
return of(null);
}
})
).subscribe(myObservable1 | myObservable2) => {
So if condition is false I only have to perform one request, if the condition is true, I have to chain the first request to the following one, they are essentially two requests to the server api.
Is there a better solution without returning that null?
Is there any conditional operator in RxJs?
Thanks!
Another possibility is to use the operator iif in a SwitchMap.
https://www.learnrxjs.io/learn-rxjs/operators/conditional/iif
https://rxjs-dev.firebaseapp.com/api/index/function/iif
but it can restrain the possibility to control specfic
conditions on your Observable :
myObservable1
.pipe(
switchMap(result1 =>
iif(() => condition
, myObservable2
, myObservable1
)
)
.subscribe(result => console.log(result));
Where you can replace 'condition' by a function returning a boolean.
With a function :
myObservable1
.pipe(
switchMap(result1 =>
iif(() => test(result1)
, myObservable2
, myObservable1
)
)
.subscribe(result => console.log(result));
test(result1) : boolean {
if(result1){
// the iif() will return myObservable2
return true;
}else{
/: the iif() will return myObservable1
return false ;
}
}
Like #amjuhire said , you can write with a filter and a switchMap :
myObservable1.pipe(
filter((result1) => condition)
switchMap((result1: MyObservable1) => {
return myObservable2;
})
).subscribe(result2 => { ... })
Another possibility given your example :
myObservable1.pipe(
switchMap((result1: MyObservable1) => {
if (condition) {
return myObservable2;
} else {
return of(result1);
}
})
subscribe(result => console.log(result));
Or using EMPTY in the switchMap :
myObservable1.pipe(
switchMap((result1: MyObservable1) => {
if (condition) {
return myObservable2;
} else {
// Observable that immediately completes
return EMPTY;
}
})
subscribe(result2 => console.log(result2));
The problem here is that we don't know the type in your observable.
So i can't judge wich way is the better.
It also depends on how you want to handle the success/error between the different calls of your observable.
No need to return of(null), you should use the RxJs filter operator
myObservable1.pipe(
filter((result1) => condition)
switchMap((result1: MyObservable1) => {
return myObservable2;
})
).subscribe((result2) => { ... })
In my understanding, you shouldn't use filter operator because in that case you wouldn't get any value.
myObservable1.pipe(
switchMap((value) => {
return iif(() => condition, myObservable2, of(value));
})
).subscribe((value) => console.log(value) // either from myObservable1 or from myObservable2)
I don't know your real code, this is the pseudo code, and I don't know which rxjs version are you using now, but you can do something like below:
assuming you are using rxjs 6:
iif(condition, obervable1, concatMap(observable1, observable2))
.subscribe()

Resources