结合可观察量和按日期排序

时间:2018-03-26 19:30:36

标签: javascript rxjs observable

我有2个BehaviorSubjects和2个observables:

private payments = new BehaviorSubject(<Payment[]>[]);
payments$: Observable<Payment[]> = this.payments.asObservable();

private purchases = new BehaviorSubject(<Purchase[]>[]);
purchases$: Observable<Purchase[]> = this.purchases.asObservable();

我想在服务中访问,将值组合成1个数组并按日期排序。我试图做一些像:

let transactions = Rx.Observable.forkJoin(this.payments$, this.purchases$).map(([x, y]) => // do sorting )}

但它不起作用。我认为这与我需要subscribe到流以获得真实值的事实有关。但是,我希望transactionspayments$purchases$保持同步,并在调用payments.next(...)purchases.next(...)时为其组合发出新值。

这可能吗?

1 个答案:

答案 0 :(得分:1)

您的想法是正确的(假设您将订阅流)但您使用了错误的运算符,因为async function set_survey_questions(response, this_survey, response_survey) { let sur_questions = QuestionsService.get({ actsern: this_survey.actsern }); await sur_questions.$promise; try { for (const quest in response_survey) { await next_question(response, this_survey, response_survey, sur_questions, quest); } console.log("Uploaded successfully all questions"); } catch (reason) { console.log(reason); } } 仅在完成forkJoinpayments$时才会发出。如果您只想一直发射对(即使没有完成流),那么只需使用purchases$

combineLatest

const transactions = Rx.Observable.combineLatest( payments$, purchases$, ).map(([payments, purchases]) => /* do sorting */); 发出时,它会从payments$获取最新值,并将两者作为数组发出。 当purchases$发出时,它会从purchases$获取最新值并将其作为数组发送。

我不知道你的情况如何,但你也可以查看https://www.learnrxjs.io/operators/combination/zip.html

区别在于: 当payments$发出时,它等待payments$发出并以阵列形式发出。 当purchases$发出时,它等待purchases$发出并以阵列形式发出。

编辑:示例:http://jsfiddle.net/khxkgwf8/