ReactiveX 学习笔记(13)基础类型

Key Types and Life Management

本文主题是 Rx 中的基础类型 Subject 类及其生命周期的管理。

公共代码

  • RxNET
private static void WriteSequenceToConsole(IObservable<string> sequence)
{
sequence.Subscribe(Console.WriteLine);
}
  • RxSwift
extension ObservableType {
func addObserver(_ id: String) -> Disposable {
return subscribe { print("Subscription:", id, "Event:", $0) }
}
}
func writeSequenceToConsole<O: ObservableType>(name: String, sequence: O) -> Disposable {
return sequence.subscribe { event in
print("Subscription: \(name), event: \(event)")
}
}

Subject<T>

Subject<T>:同时实现了IObservable<T>和IObserver<T>。

  • RxNET
var subject = new Subject<string>();
WriteSequenceToConsole(subject);
subject.OnNext("a");
subject.OnNext("b");
subject.OnNext("c");
/*
a
b
c
*/
var subject = new Subject<string>();
subject.OnNext("a");
WriteSequenceToConsole(subject);
subject.OnNext("b");
subject.OnNext("c");
/*
b
c
*/
  • RxJava
val subject = PublishSubject.create<Int>()
subject.onNext(1)
subject.subscribe { println(it) }
subject.onNext(2)
subject.onNext(3)
subject.onNext(4)
/*
2
3
4
*/
  • RxSwift
let disposeBag = DisposeBag()
let subject = PublishSubject<String>()
subject.addObserver("1").disposed(by: disposeBag)
subject.onNext("
上一篇:20172328 2018-2019《Java软件结构与数据结构》第六周学习总结


下一篇:P1012 拼数 字符串