我已经明白我在哪里犯了错误。为了解决这个问题,我接下来做了:
- 创建自定义
observe(on: Schedular)
. 所以它看起来像这样(将这些函数添加到扩展中Signal
):
func customObserve(on scheduler: DateScheduler, interval: Int, leeway: Int) -> Signal<Value, Error> {
return customFlatMapEvent(Signal.Event.observe(on: scheduler, interval: DispatchTimeInterval.seconds(interval), leeway: DispatchTimeInterval.seconds(leeway)))
}
func customFlatMapEvent<U, E>(_ transform: @escaping Event.CustomTransformation<U, E>) -> Signal<U, E> {
return Signal<U, E> { output, lifetime in
let input = transform(output.send, lifetime)
lifetime += self.observe(input)
}
}
还添加这个
extension Signal.Event {
typealias CustomTransformation<U, E: Swift.Error> = (@escaping Signal<U, E>.Observer.Action, Lifetime) -> Signal<Value, Error>.Observer.Action
static func observe(on scheduler: DateScheduler, interval: DispatchTimeInterval, leeway: DispatchTimeInterval) -> CustomTransformation<Value, Error> {
return { action, lifetime in
lifetime.observeEnded {
scheduler.schedule {
action(.interrupted)
}
}
return { event in
scheduler.schedule(after: scheduler.currentDate, interval: interval, leeway: leeway) {
if !lifetime.hasEnded {
action(event)
}
}
}
}
}
}
为观察创建绑定didFinishLaunchingWithOptions
reactive.makeBindingTarget { appDeleg, value in
print("SUCCESS")
print(value)
} <~ signalSchedular.customObserve(on: schedular, interval: 10, leeway: 1)
并模拟异步代码
DispatchQueue.main.async { [observerSchedular] in
observerSchedular.send(value: "Hello World")
observerSchedular.sendCompleted()
}
- 定义的全局属性
private let (signalSchedular, observerSchedular) = Signal<String, Never>.pipe(),
let schedular = SomeDateScheduler()
- 更改了自定义日期计划
class SomeDateScheduler : DateScheduler {
var currentDate: Date
init() {
self.currentDate = Date()
}
func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? {
action()
return nil
}
func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? {
if case .seconds(let sec) = interval {
let time = DispatchTime.now() + DispatchTimeInterval.seconds(sec)
let queue = DispatchQueue(label: "sads", qos: .utility, attributes: .concurrent)
queue.asyncAfter(deadline: time) { [weak self] in
_ = self?.schedule(after: date) {
action()
}
}
DispatchQueue.main.asyncAfter(deadline: time) { [weak self] in
_ = self?.schedule(after: date) {
action()
}
}
}
return nil
}
func schedule(_ action: @escaping () -> Void) -> Disposable? {
action()
return nil
}
}