阅读 383

RxSwift 之 Observable

Single

  • 发出一个元素,或一个 error 事件

  • 不会共享附加作用

  • let obserable5 = Single<[String : Any]>.create { single in

           //成功
               single(.success(["state" : "success"]))
           // 失败
    复制代码

    // let error = NSError(domain: "失败", code: 0, userInfo: nil) // single(.error(error))

               return Disposables.create();
           }
           obserable5.subscribe { (onNext) in
               print("成功 : ",onNext)
           } onFailure: { (error) in
               print("失败")
           } onDisposed: {
               print("销毁")
           }
    复制代码

Completable

        let obserable6 = Completable.create { (completable) -> Disposable in
            let error = NSError(domain: "Completable 失败", code: 0, userInfo: nil)
            completable(.error(error))
            completable(.completed)
            return Disposables.create();
        }
        
        obserable6.subscribe {
            print("完成")
        } onError: { (error) in
            print(error)
        } onDisposed: {
            print("销毁")
        }

completed
Error Domain=Completable 失败 Code=0 "(null)"
销毁
复制代码

Maybe

func generateString() -> Maybe<String> {
    return Maybe<String>.create { maybe in
        maybe(.success("RxSwift"))

        // OR

        maybe(.completed)

        // OR

        maybe(.error(error))

        return Disposables.create {}
    }
}

generateString()
    .subscribe(onSuccess: { element in
        print("Completed with element \(element)")
    }, onError: { error in
        print("Completed with an error \(error.localizedDescription)")
    }, onCompleted: {
        print("Completed with no element")
    })
    .disposed(by: disposeBag)
复制代码

Signal

在同样的场景中,Signal 不会把上一次的点击事件回放给新观察者,而只会将订阅后产生的点击事件,发布给新观察者

             let obserable7 = button.rx.tap.asSignal();
        event = button.rx.tap.asSignal()
        let observerAction: () -> Void = { [self] in tapActin() }
        event!.emit(onNext: observerAction)

 func tapActin() {
        print("按钮点击弹出")
        let newObserver: () -> Void = { print("内部监听弹窗") }
        event!.emit(onNext: newObserver)


    }


打印 点击第一次
按钮点击弹出
点击第二次
按钮点击弹出
内部监听弹窗
复制代码

ControlEvent

ControlEvent 专门用于描述 UI 控件所产生的事件,它具有以下特征:

  • 不会产生 error 事件
  • 一定在 MainScheduler 订阅(主线程订阅)
  • 一定在 MainScheduler 监听(主线程监听)
  • 共享附加作用
文章分类
iOS
文章标签