【问题标题】:How do I observe two rx sequences and subscribe with two closure arguments?如何观察两个 rx 序列并订阅两个闭包参数?
【发布时间】:2021-06-10 13:39:22
【问题描述】:

我想观察两个behaviorRelays 和一个observer,等待两个relays 发出它们的值,然后在subscription 中有两个单独的closure arguemts,每个relay 一个。像这样的:

let one = firmwareService.basicIODeviceUnit.compactMap { $0?.canBeUpdated }
let two = firmwareService.motorDeviceUnit.compactMap { $0?.canBeUpdated }
        
Observable.of(one, two).flatMap{ $0 }.subscribe(onNext: { a, b in
    print("--", a, b)
}).disposed(by: disposeBag)

上面的代码是不允许的。像mergezip 这样的运算符似乎将两个继电器捆绑到一个闭包参数中,所以我猜他们不会工作。我用什么?

我已经浏览过这个帖子,所以应该是可以的,但是我无法理解它,因为我使用了swift RxJS Subscribe with two arguments

【问题讨论】:

    标签: ios swift observable rx-swift


    【解决方案1】:

    我不确定你的意思,因为zip 完全符合你的要求。 combineLatest也是如此。

    let one = firmwareService.basicIODeviceUnit.compactMap { $0?.canBeUpdated }
    let two = firmwareService.motorDeviceUnit.compactMap { $0?.canBeUpdated }
    
    Observable.zip(one, two)
        .subscribe(onNext: { a, b in
            print("--", a, b)
        })
        .disposed(by: disposeBag)
    

    【讨论】:

    • 啊,好的,谢谢!我想我的语法错误。我写了类似Observable.of(one,two).zip().subscribe(onNext: { a, b 的东西,结果出错了。非常感谢您清除它! :)
    【解决方案2】:

    你可以使用 combineLatest:

    combineLatest 是一个运算符,当值取决于其他一些 Observable 的混合时,您要使用它。 当两个 Observable 中的任何一个发出 item 时,通过指定的闭包组合每个 Observable 发出的最新 item,并根据这个闭包的结果发出 item。

    请参考以下 - combineLatest meduim link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 2023-03-31
      相关资源
      最近更新 更多