【问题标题】:How can I read the value of an RxSwift property? <Driver>Bool如何读取 RxSwift 属性的值? <驱动程序>布尔
【发布时间】:2021-10-12 15:05:23
【问题描述】:

我想读取一个属性的值

var checkInEnabled: Driver<Bool> { get }

我只需要在类加载后运行一次代码,所以我不想使用类似的东西:

roomStatus.checkInEnabled
      .drive { [weak self] enabled in
        if !enabled {
          // do something everytime it changes
        }
      }.disposed(by: disposeBag)

而是像这样:

if roomStatus.checkInEnabled {
//only do something now
}

感谢阅读,

【问题讨论】:

  • 据我了解,Driver 是一个序列。如果该序列没有发出任何内容,则它没有要读取的值。听起来您正在尝试做一些与 Reactive 模型作斗争的事情。无论您尝试使用 if 检查完成什么,都应该响应 Driver 发出的值。
  • @ScottThompson 是正确的。 Driver 不存储状态,它发出值。您的驱动程序中没有要查询的 Bool。
  • 如果你能更好地解释你想要做什么,它可能会有所帮助。 checkInEnabled 是否与您要运行代码的类在同一类中?

标签: swift rx-swift


【解决方案1】:

使用 take(1) 运算符

roomStatus.checkInEnabled
      .take(1)
      .drive { [weak self] enabled in
        if !enabled {
           // ~~~
        }
      }.disposed(by: disposeBag)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多