【问题标题】:ReactiveX how to pause observableReactiveX如何暂停可观察
【发布时间】:2016-05-25 18:59:39
【问题描述】:

我在 iOS/Swift (RxSwift) 中使用 ReactiveX

假设我有一个 observable:

let dataUpdates = ...

我订阅的内容:

dataUpdates.subscribeNext({ data in
    // update tableView with data
    // maybe move to a difference cell with an animation
})

如果我在制作动画时收到更新,我不想在动画结束之前收到下一次更新(我也不想丢失动画期间发生的更新)。

所以我只需要暂停dataUpdates observable 的发射。

我怎样才能做到这一点?

【问题讨论】:

  • 这个问题很老了,但也许你还没有找到答案。除非您的 Observable 支持背压(以其他方式而不是在某个阈值后丢弃排放)处理,并且您不能简单地阻止排放进入该 observable,否则您无能为力(afaik),因为反应式编程是基于推而不是拉(背压是拉机制)。
  • 我实现了一个subscribeNextAndWait 解决了我的问题。

标签: ios swift reactive-programming reactivex


【解决方案1】:

使用 BehaviorSubject 创建一个暂停和恢复更新的阀门。请注意,您将需要dataUpdates 中的一些背压支持(即缓冲),以便在阀门关闭时到达更新。

所以在伪代码中(我不会编写 switft 代码,请原谅我的语法)

// create a BehaviorSubject with default value true. It will always emit
// the latest value when subscribed to, thus it is kind of a variable
let valve = BehaviorSubject(value: true)

// we are only interested to get one `true` value. When the latest value
// received by the valve is `true`, this will give a value immediately when
// subscribed to. When the latest value is `false`, this will not give
// any events until it is true.
let openValve = valve.filter{$0}.take(1)

// for each data update, pass it through if the valve is open and otherwise
// start waiting for it to turn true
let pauseableDataUpdates = dataUpdates.concatMap{update in openValve.map { _ in update}}

// now when you start rendering, you do
valve.on(.Next(false))

// and after animation is done, you do
valve.on(.Next(true))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多