链接依赖的 observables [英] Chaining dependent observables

查看:59
本文介绍了链接依赖的 observables的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建依赖 API 调用,其中第二个调用需要第一个调用返回的值.首先想到的是使用 flatMap

I need to create dependent API calls where the second one needs a value returned by the first one. First thing that comes to mind is using flatMap

ApiManager.shared
    .createReport(report: report)
    .flatMap { (report) -> Observable<Report> in
        return ApiManager.shared.createReportStep(reportID: report.ID)
    }

createReport 返回 Observable 成功调用后返回更新的 Report 模型(带 ID),之后我需要调用 API创建报告步骤,其中需要 report.ID.

createReport returns Observable<Report> where after successfull call returns updated Report model(with ID), after that I need to call API to create report step, where report.ID is needed.

该代码的一切看起来和工作正常,但是当我需要在每个步骤(createReportcreateReportStep)之后做一些事情时,问题就来了.我将代码放在 onNext 块中,但在两个步骤都完成后,它只被调用一次.

Everything looks and works fine with that code, but the problem comes when I need to do something after each of these steps(createReport and createReportStep). I placed code in onNext block, but it is called only once, after both of the steps are completed.

有没有办法在两个步骤后接收 onNext 信号?我可以使用这样的东西:

Is there a way to receive onNext signal after both steps? I could use something like this:

ApiManager.shared
      .createReport(report: report)
      .concat(ApiManager.shared.createReportStep(reportID: report.ID))

哪个会像我想要的那样发出两个信号,但又从哪里获取更新的 report.ID 以传递给 createReportStep?

Which would emmit two signals like I want, but then again where do I get updated report.ID from to pass to createReportStep?

推荐答案

如果您不介意时间组件并且只需要访问 report 返回的内容createReportStep(reportID:),你可以在 flatMap 的块

If you don't mind the time component and only need to have access to both report and what is returned by createReportStep(reportID:), you could go with creating a tuple in flatMap's block

ApiManager.shared
    .createReport(report: report)
    .flatMap { (report) -> Observable<Report> in
        return ApiManager.shared.createReportStep(reportID: report.ID)
            .map { (report, $0) }
    }

生成的 observable 将在元组中包含两个结果.

The resulting observable would contain both results in a tuple.

如果时间部分很重要,您可以执行以下操作

If the time component is important, you could do the following

let report = ApiManager.shared
  .createReport(report: report)
  .share()

let reportStep = report.map { $0.ID }.flatMap(ApiManager.shared.createReportStep)

Observable.concat([report, reportStep])

这里,重要的是 share 调用.它将确保 createReport 只执行一次它的工作,但是你会根据要求有两个下一个事件.

Here, the important bit is the share call. It will ensure createReport performs its work only once, but you would have two next events as requested.

这篇关于链接依赖的 observables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆