RxSwift干货RXswiftRxSwift

RxSwift文档翻译1-Creating and Subscr

2017-05-31  本文已影响328人  小白猿

近期学习RxSwift查看过简书的一篇文章,是记录其学习过程,但是由于是在2015年左右记录的,和现在的版本有一定的出入,所以我想根据官方提供的playground摘录翻译一下现在的版本的函数,目前我下载是的是3.5.0版本

0. 前言

援引以前以前学习的一篇文章的前期准备工作

SupportCode

在进入正题之前,先看下项目里的SupportCode.swift,主要为 playground 提供了两个便利函数。一个是example 函数,专门用来写示例代码的,统一输出log便于标记浏览,同时还能保持变量不污染全局

swift
public func example(description: String, action: () -> ()) { 
    print("\n--- \(description) example ---") 
    action() 
}

另一个是delay函数,通过dispatch_after用来演示延时的:

swift
public func delay(delay:Double, closure:()->()) { 
    dispatch_after( 
        dispatch_time( 
            DISPATCH_TIME_NOW, 
            Int64(delay * Double(NSEC_PER_SEC)) 
        ), 
        dispatch_get_main_queue(), closure) 
}

下面开始正式进入官方playground进行翻译

Creating and Subscribing to Observables

example("never") {
    let disposeBag = DisposeBag()
    let neverSequence = Observable<String>.never()
    
    let neverSequenceSubscription = neverSequence
        .subscribe { _ in
            print("This will never be printed")
    }
    
    neverSequenceSubscription.disposed(by: disposeBag)
}

// 控制台
--- never example ---

example("empty") {
    let disposeBag = DisposeBag()
    
    Observable<Int>.empty()
        .subscribe { event in
            print(event)
        }
        .disposed(by: disposeBag)
}

// 控制台打印的结果:
--- empty example ---
completed

// 官方问答note:
本例中将创建可观察序列和订阅可观察序列链接在一起写的
example("just") {
    let disposeBag = DisposeBag()
    
    Observable.just("🔴")
        .subscribe { event in
            print(event)
        }
        .disposed(by: disposeBag)
}

// 控制台打印的结果
--- just example ---
next(🔴)
completed
example("of") {
    let disposeBag = DisposeBag()
    
    Observable.of("🐶", "🐱", "🐭", "🐹")
        .subscribe(onNext: { element in
            print(element)
        })
        .disposed(by: disposeBag)
}
// 控制台打印结果:
--- of example ---
🐶
🐱
🐭
🐹

// 本文作者修改例子
   Observable.of("🐶", "🐱", "🐭", "🐹")
                .subscribe({ e in
                    print(e)
                })
                .disposed(by: disposeBag)

// 控制台打印结果:
--- of example ---
next(🐶)
next(🐱)
next(🐭)
next(🐹)
completed

以上两个例子的区别:在于打印事件和打印元素的区别,此处在官方文档出有一段解释

This example also introduces using the subscribe(onNext:) convenience method. Unlike subscribe(_:), which subscribes an event handler for all event types (Next, Error, and Completed), subscribe(onNext:) subscribes an element handler that will ignore Error and Completed events and only produce Next event elements. There are also subscribe(onError:) and subscribe(onCompleted:) convenience methods, should you only want to subscribe to those event types. And there is a subscribe(onNext:onError:onCompleted:onDisposed:) method, which allows you to react to one or more event types and when the subscription is terminated for any reason, or disposed, in a single call:

someObservable.subscribe(
    onNext: { print("Element:", $0) },
    onError: { print("Error:", $0) },
    onCompleted: { print("Completed") },
    onDisposed: { print("Disposed") }
)

大意为:
本示例还介绍了使用subscribe(onNext :)方便的方法。 不同于subscribe(_ :),它为所有事件类型(Next,Error和Completed)订阅事件处理程序,subscribe(onNext:) 订阅一个将忽略Error和Completed事件并仅生成Next事件元素的元素处理程序。 还有subscribe(onError :)和subscribe(onCompleted :)方便的方法,如果你只想订阅这些事件类型。 并且有一个订阅(onNext:onError:onCompleted:onDisposed :)方法,它允许您对一个或多个事件类型做出反应,并且当订阅由于任何原因而被终止或在一个调用中被处理时

example("from") {
            let disposeBag = DisposeBag()
            let swiftArray = ["🐶", "🐱", "🐭", "🐹"]
            Observable.from(swiftArray)
                .subscribe(onNext: { print($0) })
                .disposed(by: disposeBag)
        }

控制台打印的结果:
--- from example ---
🐶
🐱
🐭
🐹

本例中还演示了通过通过默认参数$0代替指定的名称的参数

example("create") {
            let disposeBag = DisposeBag()
            
            let myJust = { (element: String) -> Observable<String> in
                return Observable.create { observer in
                    observer.on(.next(element))
                    observer.on(.completed)
                    return Disposables.create()
                }
            }
            
            myJust("🔴")
                .subscribe { print($0) }
                .disposed(by: disposeBag)
        }

// 控制台打印的结果:
--- create example ---
next(🔴)
completed
example("range") {
    let disposeBag = DisposeBag()
    
    Observable.range(start: 1, count: 10)
        .subscribe { print($0) }
        .disposed(by: disposeBag)
}
--- range example ---
next(1)
next(2)
next(3)
next(4)
next(5)
next(6)
next(7)
next(8)
next(9)
next(10)
completed
example("repeatElement") {
            let disposeBag = DisposeBag()
            
            Observable.repeatElement("🔴")
                .take(3)
                .subscribe(onNext: { print($0) })
                .disposed(by: disposeBag)
        }

// 控制台打印的结果:
--- repeatElement example ---
🔴
🔴
🔴

example("generate") {
    let disposeBag = DisposeBag()
    
    Observable.generate(
            initialState: 0,
            condition: { $0 < 3 },
            iterate: { $0 + 1 }
        )
        .subscribe(onNext: { print($0) })
        .disposed(by: disposeBag)
}
// 控制台打印的结果:
--- generate example ---
0
1
2
example("deferred") {
            let disposeBag = DisposeBag()
            var count = 1
            
            let deferredSequence = Observable<String>.deferred {
                print("Creating \(count)")
                count += 1
                
                return Observable.create { observer in
                    print("Emitting...")
                    observer.onNext("🐶")
                    observer.onNext("🐱")
                    observer.onNext("🐵")
                    return Disposables.create()
                }
            }
            
            print("第1次订阅")
            deferredSequence
                .subscribe(onNext: { print($0) })
                .disposed(by: disposeBag)
            
            print("第2次订阅")
            deferredSequence
                .subscribe(onNext: { print($0) })
                .disposed(by: disposeBag)
        }

// 控制台打印的结果:
--- deferred example ---
第1次订阅
Creating 1
Emitting...
🐶
🐱
🐵
第2次订阅
Creating 2
Emitting...
🐶
🐱
🐵
example("error") {
            let disposeBag = DisposeBag()
            
            let error = NSError(domain: "domin", code: 0, userInfo: nil)
            
            Observable<Int>.error(error)
                .subscribe { print($0) }
                .disposed(by: disposeBag)
        }

// 控制台打印的结果:
--- error example ---
error(Error Domain=domin Code=0 "(null)")
      example("doOn") {
            let disposeBag = DisposeBag()
            
            Observable.of("🍎", "🍐", "🍊", "🍋")
                .do(onNext: { print("Intercepted:", $0) }, onError: { print("Intercepted error:", $0) }, onCompleted: { print("Completed")  })
                .subscribe(onNext: { print($0) })
                .disposed(by: disposeBag)
        }

// 控制台打印的结果:
--- doOn example ---
Intercepted: 🍎
🍎
Intercepted: 🍐
🍐
Intercepted: 🍊
🍊
Intercepted: 🍋
🍋
Completed

官方文档补充
There are also doOnNext(:), doOnError(:), and doOnCompleted(_:) convenience methods to intercept those specific events, and doOn(onNext:onError:onCompleted:) to intercept one or more events in a single call.

翻译为
还有doOnNext(_ :),doOnError(_ :)和doOnCompleted(_ :)方便的方法来拦截那些特定的事件,并且doOn(onNext:onError:onCompleted :)在一个调用中拦截一个或多个事件。

下一节:RxSwift文档翻译2--Working with Subjects

本文部分内容参考自
[整理]RxSwift完全入坑手册](http://www.jianshu.com/p/76211eed0ab3)

上一篇下一篇

猜你喜欢

热点阅读