2017-04-26 52 views
0

假設我有一個可用於啓動和停止(切換)操作的按鈕。RxSwift:重複(完成)流

let toggleStream: Observable<Bool> = toggleBtn.rx.tap.scan(false) { state, _ in !state } 

我有另一個流,不斷髮出整數。

let emitter = Observable<Int>.interval(2.0, scheduler: timerScheduler) 

現在我想用撥動流啓動和停止第二流的發射。這是我的方法:

Observable.combineLatest(toggleStream, emitter) { shouldEmit, evt in 
    return (shouldEmit, evt) 
}.takeWhile{ (shouldEmit, evt:Int) in 
    return shouldEmit == true 
}.map {(_, evt) in 
    return evt 
} 

這是第一次很好用。我可以按下按鈕,Observable開始發出其Ints。也停止工作。可悲的是,我無法再次啓動它,因爲流已完成。當用戶再次切換按鈕時,如何重新啓動/重試/重複?

回答

1

這就是我在操場上做到的。你應該可以外推:

//: Playground - noun: a place where people can play 

import RxSwift 

let toggleButton = PublishSubject<Void>() 
let toggleStream: Observable<Bool> = toggleButton 
    .scan(false) { state, _ in !state } 
    .debug() 
    .shareReplayLatestWhileConnected() 

let emit = toggleStream 
    .filter { $0 } 
    .flatMapLatest { _ in 
     Observable<Int>.interval(2.0, scheduler: MainScheduler.instance) 
      .takeUntil(toggleStream.filter { !$0 }) 
    } 


_ = emit.subscribe({ 
    print($0) 
}) 

toggleButton.onNext() 
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5.0) { 
    toggleButton.onNext() 
} 
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 11.0) { 
    toggleButton.onNext() 
} 
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 17.0) { 
    toggleButton.onNext() 
} 

import PlaygroundSupport 
PlaygroundPage.current.needsIndefiniteExecution = true