我在项目中使用ReactiveSwift,但我想知道PublishSubject的等效功能是什么?
例如在RXSwift中,我们可以做到:
let disposeBag = DisposeBag()
let pubSubj = PublishSubject<String>()
pubSubj.on(.next("(next 1")) //event emitted to no subscribers
pubSubj.subscribe({ //subscriber added, but no replay of "next 1"
print("line: \(#line),", "event: \($0)")
})
.disposed(by: disposeBag)
pubSubj.on(.next("(next 2")) //event emitted and received by subscriber
pubSubj.onError(MyError.error1) //emits error and terminates sequence
pubSubj.on(.next("next 3")) //pubSubj cannot emit this event
/* prints:
line: 8, event: next((next 2)
line: 8, event: error(error1)
*/
答案 0 :(得分:1)
ReactiveSwift
没有像Subject这样的单一类型,它既可以作为信号的输入,也可以作为信号的输出。相反,您可以使用Signal.pipe()
创建输入及其相应的输出信号:
import ReactiveSwift
enum MyError: Error { case error1 }
let (lifetime, token) = Lifetime.make()
let (signal, input) = Signal<String, MyError>.pipe()
input.send(value: "1")
signal
.take(during: lifetime)
.observe {
print("line: \(#line),", "event: \($0)")
}
input.send(value: "2")
input.send(error: .error1)
input.send(value: "3")
/* prints:
line: 14, event: VALUE 2
line: 14, event: FAILED error1
*/