• AnyObserver
    • 例如:

    AnyObserver

    AnyObserver 可以用来描叙任意一种观察者。

    例如:


    打印网络请求结果:

    1. URLSession.shared.rx.data(request: URLRequest(url: url))
    2. .subscribe(onNext: { data in
    3. print("Data Task Success with count: \(data.count)")
    4. }, onError: { error in
    5. print("Data Task Error: \(error)")
    6. })
    7. .disposed(by: disposeBag)

    可以看作是:

    1. let observer: AnyObserver<Data> = AnyObserver { (event) in
    2. switch event {
    3. case .next(let data):
    4. print("Data Task Success with count: \(data.count)")
    5. case .error(let error):
    6. print("Data Task Error: \(error)")
    7. default:
    8. break
    9. }
    10. }
    11. URLSession.shared.rx.data(request: URLRequest(url: url))
    12. .subscribe(observer)
    13. .disposed(by: disposeBag)

    用户名提示语是否隐藏:

    1. usernameValid
    2. .bind(to: usernameValidOutlet.rx.isHidden)
    3. .disposed(by: disposeBag)

    可以看作是:

    1. let observer: AnyObserver<Bool> = AnyObserver { [weak self] (event) in
    2. switch event {
    3. case .next(let isHidden):
    4. self?.usernameValidOutlet.isHidden = isHidden
    5. default:
    6. break
    7. }
    8. }
    9. usernameValid
    10. .bind(to: observer)
    11. .disposed(by: disposeBag)

    下一节将介绍 Binder 以及 usernameValidOutlet.rx.isHidden 的由来。