Reputation: 567
I've 2 observables (async). The first one returns an array of status with a rank for each status. The second one returns an array of users with the status of each user.
I'm trying to output a user list sorted by status.
This is what I've tried :
const sortedUserList$: Subject<any> = new Subject();
this.getStatusList()
.pipe(take(1))
.subscribe(statusList=> {
this.getUserList()
.pipe(take(1))
.subscribe(userList=> {
// ... sorting algo using both statusList and userList
sortedUserList$.next(centersPlanning);
});
});
Obviously, it doesn't work because statusList
isn't available in the second subscribe
because it's out of its scope.
It's also doesn't look like nesting two subscribte
this way is the right way of doing things using rxJS.
I've also tried using mergeMap
but with no more sucess.
Thanks and regards
Upvotes: 1
Views: 175
Reputation: 2682
You might use forkJoin
from rxjs. Try something like this:
import { forkJoin, of, Subject } from 'rxjs'
import {take, delay} from 'rxjs/operators'
sortedUserList: Subject<any> = new Subject();
//For demonstration purposes
getStatusList() {
return of('first').pipe(
delay(2000)
);
}
//For demonstration purposes
getUserList() {
return of('second').pipe(
delay(1000)
)
}
ngOnInit() {
forkJoin(
this.getStatusList(),
this.getUserList()
).pipe(
take(1)
).subscribe(resp => {
console.log(resp) // ['first', 'second']
//Do whatever you want with both responses here.
this.sortedUserList$.next(centersPlanning)
})
}
Check it stackblitz
Upvotes: 2