如何组合3个firebase observable而不会丢失动态更新

时间:2017-01-21 22:31:58

标签: firebase rxjs reactive-programming observable

我有3个并行的firebase需要。我需要将它们作为单个对象加入。代码如下:

import {Http} from "@angular/http";
import {AngularFireDatabase} from "angularfire2";
import {Thread} from "../model/thread";
import {Message} from "../model/message";
import {Participant} from "../model/participant";

constructor(private  http: Http, private db:AngularFireDatabase) { }

loadUserThreads(uid): Observable<AllUserData> {
return Observable.forkJoin([
  this.db.list('participant/' + uid + '/threads').first(),
  this.db.list('participant/' + uid + '/messages').first(),
  this.db.list('participant/' + uid + '/participants').first()
])
  .map((data:any[]) => {
    let threads: Thread[] = data[0];
    let messages: Message[] = data[1];
    let participants: Participant[] = data[2];
    let AllUserData = {
      threads: threads,
      messages: messages,
      participants: participants
    }
    return AllUserData;
  })
  }

这项工作并返回我需要的确切格式,即使用此界面:

export interface AllUserData {
  participants: Participant[];
  threads: Thread[];
  messages: Message[];
}

问题是forkJoin不会在没有.first()所有firebase observable的情况下运行。如果我使用.first()来完成所有的firebase observable,我会丢失动态更新,这就是为什么我首先使用firebase。我怎样才能充分利用这两个世界? - 保持firebase的可观察性,但可以像我的界面格式一样加入它们吗?我正在把头发拉出来。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:10)

而不是.forkJoin(...),您可以使用.combineLatest(...)

我也简化你的map

Observable.combineLatest(
  this.db.list('participant/' + uid + '/threads'),
  this.db.list('participant/' + uid + '/messages'),
  this.db.list('participant/' + uid + '/participants')
)
.map(([threads, messages, participants]: [Thread[], Message[], Participant[]]) =>
  ({ threads, messages, participants })
)