1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
private func filterElem() { exampleOf(msg: "过滤操作符: filter", action: { bag in let obv = Observable.of(1, 3, 5, 7, 9, 2, 4, 6, 8, 10) obv.filter({ $0 % 2 == 0 }).subscribe(onNext: { print($0) }, onError: { print($0) }, onCompleted: { print("完成") }, onDisposed: { print("被释放") }).disposed(by: bag) }) }
private func createAnObservable() { let observable = Observable<Data>.create({ observer in let disposeables = Disposables.create() let session = URLSession.shared session.dataTask( with: URL(string: "https://www.baidu.com")!, completionHandler: { data, resp, error in if let error = error { observer.onError(error) } observer.onNext(data!) observer.onCompleted() }).resume() return disposeables }) observable.subscribe(onNext: { print($0) }, onError: { print($0) }, onCompleted: { print("完成") }, onDisposed: { print("被释放") }).disposed(by: disposeBag) }
private func takeLastElem() { exampleOf(msg: "takeLast 操作符", action: { bag in let obv = Observable.of(1,2,3,4,5,6) obv.takeLast(1) .subscribe(onNext: { print($0) }, onError: { print($0) }, onCompleted: { print(" takeLast 的那个订阅完成") }, onDisposed: { print("释放 takeLast 订阅") }).disposed(by: bag) }) }
private func takeSomeTime() { let publish = PublishSubject<Void>() print("当前时间戳: \(Date().timeIntervalSinceReferenceDate)") publish.take(5.0, scheduler: MainScheduler.instance).subscribe(onNext: { print("发布了!") print("当前时间戳: \(Date().timeIntervalSinceReferenceDate)") }, onError: { print($0) }, onCompleted: { print("完成") print("当前时间戳: \(Date().timeIntervalSinceReferenceDate)") }, onDisposed: { print("被释放") print("当前时间戳: \(Date().timeIntervalSinceReferenceDate)") }).disposed(by: disposeBag) publish.onNext(()) }
|