我想使用Combine在代码中创建一个循环的repeat功能。我注意到,Combine并没有通过这个伟大的存储库:https://github.com/freak4pc/rxswift-to-combine-cheatsheet重复发布。这是我写的代码,可以重复2个状态。如何将其简化为更具可读性的内容,或者创建自己的repeat函数?
toggleShouldDisplay = Just<Void>(())
.delay(for: 2, scheduler:RunLoop.main)
.map({ _ in
self.shouldDisplay = true
self.didChange.send(())
})
.delay(for: 2, scheduler: RunLoop.main)
.map({ _ in
self.shouldDisplay = false
self.didChange.send(())
})
.setFailureType(to: NSError.self)
.tryMap({ _ in
throw NSError()
})
.retry(.max) // I might hit Int.max if I reduce the delays
.sink(receiveValue: { _ in
//Left empty
})发布于 2019-07-14 05:01:50
.retry(_:)操作符实际上旨在用于重试可能失败的操作,例如网络请求。听起来你需要一个计时器来代替。幸运的是,从Xcode11Beta2开始,苹果已经在基金会的Timer类中添加了对Publisher的支持。
关于您的实现的另一个备注:我假设这段代码用于BindableObject中,因为您正在访问didChange。既然didChange可以是任何类型的Publisher,为什么不使用shouldDisplay属性作为Publisher
final class MyModel: BindableObject {
var didChange: CurrentValueSubject<Bool, Never> { shouldDisplaySubject }
var shouldDisplay: Bool { shouldDisplaySubject.value }
private let shouldDisplaySubject = CurrentValueSubject<Bool, Never>(false)
private var cancellables: Set<AnyCancellable> = []
init() {
startTimer()
}
private func startTimer() {
Timer.publish(every: 2, on: .main, in: .default)
.autoconnect()
.scan(false) { shouldDisplay, _ in
!shouldDisplay
}
.assign(to: \.value, on: shouldDisplaySubject)
.store(in: &cancellables)
}
}发布于 2019-07-16 16:20:23
您可以像这样使用Timer.Publisher:
toggleShouldDisplay = Timer.publisher(every: 2, on: .main, in: .default)
.autoconnect()
.sink {
self.shouldDisplay = !self.shouldDisplay
self.didChange.send(())
}只要您使用sink(_:)订阅,autconnect()就会让Timer启动。
https://stackoverflow.com/questions/56998702
复制相似问题