gpt4 book ai didi

ios - RxSwift-启动和更新倒数计时器

转载 作者:行者123 更新时间:2023-12-01 21:25:30 31 4
gpt4 key购买 nike

我正在尝试构建一个计时器,该计时器从15秒开始,递减计数到0。
事情是,我想根据事件将计时器更新2秒。
到目前为止,这是我尝试做的事情:

struct ViewModel {
struct Input {
let add_time: Observable<Void>
}
struct Output {
let current_time: Observable<String>
let timer_over: Observable<Void>
}

private let current_time = BehaviorRelay(value: 15)
private let timer_over = PublishSubject<Void>()

func transform(input: Input) -> Output {
let current_time = self.current_time
.flatMapLatest { time in
Observable<Int>
.timer(.seconds(0), period: .seconds(1), scheduler: MainScheduler.instance)
.take(self.current_time.value + 1)
.map { "\(self.current_time.value - $0)" }
.do(onCompleted: { self.timer_over.onNext(()) })
}
return Output(
current_time: current_time,
timer_over: timer_over
)
}
}

let disposeBag = DisposeBag()

let add_time_subject = PublishSubject<Void>()
let input = ViewModel.Input(
add_time: add_time_subject.asObservable()
)
let output = ViewModel().transform(input: input)
output.current_time
.subscribe(onNext: { (time) in
print(time)
})
.disposed(by: disposeBag)
output.timer_over
.subscribe(onNext: {
print("timer_over")
})
.disposed(by: disposeBag)
问题是,当我运行 add_time_subject.onNext(()) 时,我只想在计时器未达到0秒时再将计时器更新2秒。
我该怎么办?

最佳答案

您想要实现的目标听起来像是状态机。
您可以通过将计时器操作拆分为实际的“操作”并根据触发器进行合并来实现(一个是手动的“加两秒”,另一个是自动的“减少一秒”)。
我尚未对其进行全面测试,但这可能是一个很好的起点:

enum TimerAction {
case tick
case addTwoSeconds
}

let trigger = PublishRelay<Void>()

let timer = Observable<Int>
.interval(.seconds(1), scheduler: MainScheduler.instance)
.map { _ in TimerAction.tick }

let addSeconds = trigger.map { TimerAction.addTwoSeconds }

Observable
.merge(timer, addSeconds)
.scan(into: 15) { totalSeconds, action in
totalSeconds += action == .addTwoSeconds ? 2 : -1
}
.takeUntil(.inclusive) { $0 == 0 }
.subscribe()
.disposed(by: disposeBag)

DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
trigger.accept(()) // increase the timer by two seconds after 5 seconds
}

关于ios - RxSwift-启动和更新倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63550102/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com