这也可能有点冗长,但至少应该更容易理解。随意问任何问题。
注意:我让这个对象自己开始处理,而不是返回SignalProducer
调用者将开始的 a。相反,我添加了一个只读属性,听众可以在不启动处理的情况下观察该属性。
我试图让我的观察者尽可能被动,从而使他们更“被动”而不是“主动”。这种模式应该适合您的需求,即使它有点不同。
我试图让这个例子包括:
- 来自单个工作单元的共享结果。
- 错误处理。
- 信号保留的最佳实践。
- 评论中的一般解释,因为很难找到好的教程。
- 对不起,如果我在解释你已经知道的事情。我不确定假设你已经知道多少。
- 模拟处理延迟(在生产代码中删除)。
它远非完美,但应该提供一个可以修改和扩展的可靠模式。
struct MyStruct {}
final class MyClass {
// MARK: Shared Singleton
static let shared = MyClass()
// MARK: Initialization
private init() {}
// MARK: Public Stuff
@discardableResult
func getValue() -> Signal<MyStruct, NoError> {
if !self.isGettingValue {
print("Get value")
self.start()
} else {
print("Already getting value.")
}
return self.latestValue
.signal
.skipNil()
}
var latestValue: Property<MyStruct?> {
// By using a read-only property, the listener can:
// 1. Choose to take/ignore the previous value.
// 2. Choose to listen via Signal, SignalProducer, or binding operator '<~'
return Property(self.latestValueProperty)
}
// MARK: Private Stuff
private var latestValueProperty = MutableProperty<MyStruct?>(nil)
private var isGettingValue = false {
didSet { print("isGettingValue: changed from '\(oldValue)' to '\(self.isGettingValue)'") }
}
private func start() {
// Binding with `<~` automatically starts the SignalProducer with the binding target (our property) as its single listener.
self.latestValueProperty <~ self.newValueProducer()
// For testing, delay signal to mock processing time.
// TODO: Remove in actual implementation.
.delay(5, on: QueueScheduler.main)
// If `self` were not a Singleton, this would be very important.
// Best practice says that you should hold on to signals and producers only as long as you need them.
.take(duringLifetimeOf: self)
// In accordance with best practices, take only as many as you need.
.take(first: 1)
// Track status.
.on(
starting: { [unowned self] in
self.isGettingValue = true
},
event: { [unowned self] event in
switch event {
case .completed, .interrupted:
self.isGettingValue = false
default:
break
}
}
)
}
private func newValueProducer() -> SignalProducer<MyStruct?, NoError> {
return SignalProducer<MyStruct?, AnyError> { observer, lifetime in
// Get Struct with possible error
let val = MyStruct()
// Send and complete the signal.
observer.send(value: val)
observer.sendCompleted()
}
// Don't hold on to errors longer than you need to.
// I like to handle them as close to the source as I can.
.flatMapError { [unowned self] error in
// Deal with error
self.handle(error: error)
// Transform error type from `AnyError` to `NoError`, to signify that the error has been handled.
// `.empty` returns a producer that sends no values and completes immediately.
// If you wanted to, you could return a producer that sends a default or alternative value.
return SignalProducer<MyStruct?, NoError>.empty
}
}
private func handle(error: AnyError) {
}
}
测试
// Test 1: Start processing and observe the results.
MyClass.shared
.getValue()
.take(first: 1)
.observeValues { _ in
print("Test 1 value received.")
}
// Test 2: Attempt to start (attempt ignored) and observe the same result from Test 1.
MyClass.shared
.getValue()
.take(first: 1)
.observeValues { _ in
print("Test 2 value received.")
}
// Test 3: Observe Value from Test 1 without attempting to restart.
MyClass.shared
.latestValue
.signal
.skipNil()
.take(first: 1)
.observeValues { _ in
print("Test 3 value received.")
}
// Test 4: Attempt to restart processing and discard signal
MyClass.shared.getValue()
输出:
Get value
isGettingValue: changed from 'false' to 'true'
Already getting value.
Already getting value.
(5秒后)
Test 1 value received.
Test 2 value received.
Test 3 value received.
isGettingValue: changed from 'true' to 'false'