[英]Multicasting in ReactiveCocoa 3 and ReactiveCocoa 4
Let's say I have a function that returns a SignalProducer<AnyObject?, NSError>
and I want to bind the producer to multiple MutableProperty<String>
. 假设我有一个返回SignalProducer<AnyObject?, NSError>
的函数,并且我想将生产者绑定到多个MutableProperty<String>
。 So, something like this: 因此,如下所示:
let foo = SignalProducer<AnyObject?, NSError>(value: nil)
let someProperty1 = MutableProperty<String>("")
let someProperty2 = MutableProperty<String>("")
someProperty1 <~ foo
.flatMapError { _ in
SignalProducer<AnyObject?, NoError>.empty
}
.map { _ in
return "test"
}
// someProperty2 <~ foo etc...
In order to avoid my function (eg some network stuff) being run multiple times I would need to use multicasting. 为了避免我的功能(例如某些网络设备)被多次运行,我将需要使用多播。 As far as I can tell from the CHANGELOG , startWithSignal
is the operator to use for this. 据我从CHANGELOG得知 , startWithSignal
是用于此的运算符。 However I can't seem to figure out how to do this in a declarative manner. 但是,我似乎无法弄清楚如何以声明的方式进行此操作。
So, one approach could be to make the binding in the closure of the startWithSignal
: 因此,一种方法可能是在startWithSignal
的关闭过程中进行startWithSignal
:
foo.startWithSignal { signal, disposable in
someProperty1 <~ signal
.map { _ in
return "test"
}
// someProperty2 <~ signal etc...
}
However this will obviously fail because we need to get rid of the NSError
part. 但是,这显然会失败,因为我们需要摆脱NSError
部分。 Because we're giving a Signal
(opposed to a SignalProducer
), we cannot use flatMapError
(in RAC4, catch
in RAC3). 因为我们要提供一个Signal
(与SignalProducer
相对),所以我们不能使用flatMapError
(在RAC4中,在RAC3中catch
)。 And I do not see how mapError
can do this for us? 而且我看不到mapError
如何为我们做到这一点? Lastly, I'm not even sure that this is the proper way to handle multicasting in RAC3/RAC4? 最后,我什至不确定这是否是在RAC3 / RAC4中处理多播的正确方法?
Any help is much appreciated. 任何帮助深表感谢。
Use flatMapError
(and any other operators that must take a SignalProducer
argument) before starWithSignal
在starWithSignal
之前使用flatMapError
(以及必须使用SignalProducer
参数的任何其他运算符)
let fooIgnoreError = foo
.flatMapError { _ in
SignalProducer<AnyObject?, NoError>.empty
}
fooIgnoreError.startWithSignal { signal, disposable in
someProperty1 <~ signal.map { _ in "test" }
someProperty2 <~ signal.map { _ in "test2" }
}
If the fooIgnoreError
is started only once, your underlying signal producer foo
is guaranteed to be started only once too. 如果fooIgnoreError
仅启动一次,则可以保证基础信号生成器foo
也只能启动一次。
I explained how to implement multicasting with an example here . 我在这里通过示例解释了如何实现多播 。
As for errors, you can make your property AnyProperty<Result<Value, Error>>
to be able to forward errors. 对于错误,可以使属性AnyProperty<Result<Value, Error>>
能够转发错误。 If you want the signal to terminate upon a failure, you can simply 如果您希望信号在发生故障时终止,则只需
signal.flatMapError { error in
fatalError("Error: \(error)") // or some other form of error handling, or simply ignoring the error?
return .empty
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.