如何在事件发生时取消可观察量并重新订阅(基本上我希望可观察量在另一个事件发生时跳过发射(点击取消按钮))。
详细场景:在
UISearchBar
上点击取消按钮,如何在点击取消按钮时让 observable 暂停并停止发出事件?
我在想这样的事情:
Observable.of(searchClick,historyClick).merge().debounce(0.3, scheduler: scheduler)
.takeUntil(searchBar.rx.cancelButtonClicked)
.bind(to: viewModel.search)
.disposed(by: disposeBag)
但是订阅之后就停止了。当事件发生时,我们如何重新订阅或以任何其他方式跳过发射?
我认为最好使用“.switchLatest()”运算符切换到下一个可观察值(在切换时可能处于休眠状态)。
let eventSwitch: BehaviorSubject<Observable<T>> = BehaviorSubject.create(/*initial value*/) // where T is your type of choice
let events = eventSwitch.switchLatest() // subscribe consumer to this
eventSwitch.onNext(/*new event source of type Observable<T>*/) // call this from "Cancel" button
更新
let eventSwitch = BehaviorSubject(value: Observable
.of(searchClick,historyClick)
.merge()
.debounce(0.3, scheduler: scheduler)
)
let events = eventSwitch.switchLatest()
events
.bind(to: viewModel.search)
.disposed(by: disposeBag)
// call this from "Cancel" button
eventSwitch.onNext(...)
// argument can be empty observable or 'Observable.of(searchClick,historyClick).merge().debounce(0.3, scheduler: scheduler)'