仿照RAS实现SignalProducer
SignalProducer的作用:
- 与Signal相比,Signal在调用send的时候,指定观察者动作,SignalProducer在构造时候,就指定了观察者动作;
SignalProducer的实现:
- 在执行start方法时,构造了Signal,将观察者对象添加到Signal中,指定SignalProducer的startHandler,并传入内部的obs控制对象
附代码:
struct aSignalProducer<Value, Error> {
let core: aSignalProducerCore<Value, Error>
init(_ startHandler: @escaping (aSignal<Value, Error>.aObserver) -> Void) {
self.init(aSignalCore {
let fakeDisposable = aDisposable({ print("fake Disposable") })
let (signal, obs) = aSignal<Value, Error>.pipe()
let observerDidSetup = { startHandler(obs) }
return aSignalCore<Value, Error>.Instance(signal: signal, observerDidSetup: observerDidSetup, interruptedHandle: fakeDisposable)
})
}
init(value: Value) {
self.init(aGeneratorCore<Value, Error> { observer, _ in
observer.send(value)
})
}
init(_ core: aSignalProducerCore<Value, Error>) {
self.core = core
}
@discardableResult
func start(_ observer: aSignal<Value, Error>.aObserver) -> aDisposable {
return core.start { _ in observer }
}
}
internal class aSignalProducerCore<Value, Error> {
struct Instance {
let signal: aSignal<Value, Error>
let observerDidSetup: () -> Void
let interruptedHandle: aDisposable
}
func makeInstance() -> Instance {
fatalError()
}
func start(_ generator: (_ disposable: aDisposable) -> aSignal<Value, Error>.aObserver) -> aDisposable {
fatalError()
}
}
private class aSignalCore<Value, Error>: aSignalProducerCore<Value, Error> {
let _make: () -> Instance
init(_ action: @escaping () -> Instance) {
self._make = action
}
override func makeInstance() -> aSignalProducerCore<Value, Error>.Instance {
return self._make()
}
override func start(_ generator: (aDisposable) -> aSignal<Value, Error>.aObserver) -> aDisposable {
let instance = makeInstance()
instance.signal.observe(generator(instance.interruptedHandle))
instance.observerDidSetup()
return instance.interruptedHandle
}
}
private class aGeneratorCore<Value, Error>: aSignalProducerCore<Value, Error> {
let _generator: (aSignal<Value, Error>.aObserver, aDisposable) -> Void
init(_ generator: @escaping (aSignal<Value, Error>.aObserver, aDisposable) -> Void) {
self._generator = generator
}
override func makeInstance() -> aSignalProducerCore<Value, Error>.Instance {
let fakeDisposable = aDisposable({})
let (signal, obs) = aSignal<Value, Error>.pipe()
return Instance(signal: signal, observerDidSetup: { self._generator(obs, fakeDisposable) }, interruptedHandle: fakeDisposable)
}
override func start(_ generator: (aDisposable) -> aSignal<Value, Error>.aObserver) -> aDisposable {
let instance = makeInstance()
instance.signal.observe(generator(instance.interruptedHandle))
instance.observerDidSetup()
return instance.interruptedHandle
}
}
/**
* aSignalProducer 使用方式
*/
let asps = aSignalProducer<String, NoError> { observer in
observer.send("22222")
}
let asubscriber = aSignal<String, NoError>.aObserver { event in
if case let .value(v) = event {
print(v)
} else if case .interupt = event {
print("interrupted")
}
}
asps.start(asubscriber)
网友评论