问题
I have the setup where I query firebase for list of user favourite posts.
Basically, at first I query for user likes and then for each like get the corresponding post - all in one observable sequence.
The problem arises when user dislikes the only left post. In that case (when the likes array becomes empty) nothing is fired from the observable and view is not updated (there is always at least one post present).
On the one hand, this behaviour seems logical and understandable, but on the other hand, I'm not sure how to make final Observable emit even if the input to the switchMap was empty. Maybe should change the operator.
getUserFavourites(userId = ""):Observable<Post[]>
{
if (!this.userFavourites$) {
this.userFavourites$ = this.af.database.list('/ranks_by_user/' + userId, {
query: {
limitToFirst: 50
}
}) //Emits value here (even empty array)
.switchMap((likes: any[]) => Observable.combineLatest(
likes.map(like => this.af.database.object("/posts/" + like.$key).first())
)) //Does not emit new value here if likes array was empty
.map(p => {
return p.map(cit => Post.unpack(p));
}).publishReplay(1).refCount()
}
return this.userFavourites$;
}
回答1:
Solved the problem by adding a condition inside switchMap:
Original - https://github.com/ReactiveX/rxjs/issues/1910
getUserFavourites(userId = ""):Observable<Post[]>
{
if (!this.userFavourites$) {
this.userFavourites$ = this.af.database.list('/ranks_by_user/' + userId, {
query: {
limitToFirst: 50
}
}) //Emits value here (even empty array)
.switchMap((likes: any[]) => {
return likes.length === 0 ?
Observable.of(likes) :
Observable.combineLatest(
likes.map(like => this.af.database.object("/citations/" + like.$key))
)
}) //Emits either combined observables array or empty array
.map(p => {
return p.map(cit => Post.unpack(p));
}).publishReplay(1).refCount()
}
return this.userFavourites$;
}
回答2:
.switchMap((likes) => likes.length > 0 ?
Observable.combineLatest(
likes.map(like => this.af.database.object("/posts/" + like.$key).first():
Observable.empty() // if emit empty() then .map() will not run
)
.map(...)
来源:https://stackoverflow.com/questions/41723541/rxjs-switchmap-not-emitting-value-if-the-input-observable-is-empty-array