RxSwift - Observable序列的创建方式

2020-06-11  本文已影响0人  恍然如梦_b700

1:emty

首先来一个空的序列 - 本来序列事件是Int类型的,这里调用emty函数 没有序列,只能complete

print("********emty********")
let emtyOb = Observable<Int>.empty()
_ = emtyOb.subscribe(onNext: { (number) in
    print("订阅:",number)
}, onError: { (error) in
    print("error:",error)
}, onCompleted: {
    print("完成回调")
}) {
    print("释放回调")
}

override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element {
    observer.on(.completed)
    return Disposables.create()
}

image

2: just

print("********just********")
//MARK:  just
// 单个信号序列创建
let array = ["FY_Event","LG_Kody"]
Observable<[String]>.just(array)
    .subscribe { (event) in
        print(event)
    }.disposed(by: disposeBag)

_ = Observable<[String]>.just(array).subscribe(onNext: { (number) in
    print("订阅:",number)
}, onError: { (error) in
    print("error:",error)
}, onCompleted: {
    print("完成回调")
}) {
    print("释放回调")
}

override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element {
    observer.on(.next(self._element))
    observer.on(.completed)
    return Disposables.create()
}

image

3:of

print("********of********")
//MARK:  of
// 多个元素 - 针对序列处理
Observable<String>.of("FY_Event","LG_Kody")
    .subscribe { (event) in
        print(event)
    }.disposed(by: disposeBag)

// 字典
Observable<[String: Any]>.of(["name":"FY_Event","age":18])
    .subscribe { (event) in
        print(event)
    }.disposed(by: disposeBag)

// 数组
Observable<[String]>.of(["FY_Event","LG_Kody"])
    .subscribe { (event) in
        print(event)
    }.disposed(by: disposeBag)

image

4:from

print("********from********")
// MARK:  from
Observable<[String]>.from(optional: ["FY_Event","LG_Kody"])
    .subscribe { (event) in
        print(event)
    }.disposed(by: disposeBag)

image

5:deferred

print("********defer********")
//MARK:  defer
var isOdd = true
_ = Observable<Int>.deferred { () -> Observable<Int> in
    // 这里设计我们的序列
    isOdd = !isOdd
    if isOdd {
        return Observable.of(1,3,5,7,9)
    }
    return Observable.of(0,2,4,6,8)
    }
    .subscribe { (event) in
        print(event)
    }

func run() -> Disposable {
    do {
        let result = try self._observableFactory()
        return result.subscribe(self)
    }
    catch let e {
        self.forwardOn(.error(e))
        self.dispose()
        return Disposables.create()
    }
}

image

6:rang

print("********rang********")
//MARK:  rang
Observable.range(start: 2, count: 5)
    .subscribe { (event) in
        print(event)
    }.disposed(by: disposeBag)

// 底层源码
init(start: E, count: E, scheduler: ImmediateSchedulerType) {
    self._start = start
    self._count = count
    self._scheduler = scheduler
}

override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
    let sink = RangeSink(parent: self, observer: observer, cancel: cancel)
    let subscription = sink.run()
    return (sink: sink, subscription: subscription)
}

if i < self._parent._count {
    self.forwardOn(.next(self._parent._start + i))
    recurse(i + 1)
}
else {
    self.forwardOn(.completed)
    self.dispose()
}

image

7:generate

print("********generate********")
//MARK:  generate
Observable.generate(initialState: 0,// 初始值
                    condition: { $0 < 10}, // 条件1
                    iterate: { $0 + 2 })  // 条件2 +2
    .subscribe { (event) in
        print(event)
    }.disposed(by: disposeBag)

// 数组遍历
let arr = ["FY_Event_1","FY_Event_2","FY_Event_3","FY_Event_4","FY_Event_5","FY_Event_6","FY_Event_7","FY_Event_8","FY_Event_9","FY_Event_10"]
Observable.generate(initialState: 0,// 初始值
    condition: { $0 < arr.count}, // 条件1
    iterate: { $0 + 1 })  // 条件2 +2
    .subscribe(onNext: {
        print("遍历arr:",arr[$0])
    })
    .disposed(by: disposeBag)

image

8:timer

print("********timer********")
//MARK:  timer
Observable<Int>.timer(5, period: 2, scheduler: MainScheduler.instance)
    .subscribe { (event) in
        print(event)
    }
.disposed(by: disposeBag)

// 因为没有指定期限period,故认定为一次性
Observable<Int>.timer(1, scheduler: MainScheduler.instance)
    .subscribe { (event) in
        print("111111111 \(event)")
    }
    //.disposed(by: disposeBag)

image

9:interval

print("********interval********")
//MARK:  interval
// 定时器
Observable<Int>.interval(1, scheduler: MainScheduler.instance)
    .subscribe { (event) in
        print(event)
    }
    //.disposed(by: disposeBag)

image

9:repeatElement

print("********repeatElement********")
//MARK:  repeatElement
Observable<Int>.repeatElement(5)
    .subscribe { (event) in
        // print("订阅:",event)
    }
    .disposed(by: disposeBag)

image

10:error

print("********error********")
//MARK:  error
// 对消费者发出一个错误信号
Observable<String>.error(NSError.init(domain: "lgerror", code: 10086, userInfo: ["reason":"unknow"]))
    .subscribe { (event) in
        print("订阅:",event)
    }
    .disposed(by: disposeBag)

image

11:never

print("********never********")
//MARK:  never
Observable<String>.never()
    .subscribe { (event) in
        print("走你",event)
    }
    .disposed(by: disposeBag)
print("********never********")

[图片上传中...(image-d05944-1591873354261-0)]

12:create()

let observable = Observable<String>.create{observer in
    //对订阅者发出了.next事件,且携带了一个数据"hangge.com"
    observer.onNext("hangge.com")
    //对订阅者发出了.completed事件
    observer.onCompleted()
    //因为一个订阅行为会有一个Disposable类型的返回值,所以在结尾一定要returen一个Disposable
    return Disposables.create()
}

//订阅测试
observable.subscribe {
    print($0)
}

序列的创建也是学习 RxSwift 的根基,有很多时候我遇到很多的BUG,说白了就是根基没有掌握好!

上一篇 下一篇

猜你喜欢

热点阅读