2016-11-25 59 views
0

我是新的RXSwift,我只是嘗試實現一個簡單的異步示例RXSwift簡單的異步示例?

但訂閱永遠不會被調用。

我想念什麼?

let disposeBag = DisposeBag() 

Observable<Any>.create { 

    observer in 

    DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 3) { 

     observer.onNext("done") 

     observer.onCompleted() 

    } 

    return Disposables.create() 

} 
.subscribe { print($0) } 
.addDisposableTo(disposeBag) 

================= UPDATE ======================

我試圖做一些更先進的事情,一個允許從前面傳遞值的鏈,但結果不是預期的。我想念什麼?

產量

下一個(做1 - 完成2)

我所期待的是

下一個(做1)

下一個(已完成1 - 完成2)

comple泰德

class AsyncObject { 

    func asyncTest1() -> Observable<String> { 

     return Observable<String>.create { 

      (o: AnyObserver<String>) -> Disposable in 

      DispatchQueue.main.asyncAfter(deadline: .now() + 3) { 

       o.onNext("done 1") 

       o.onCompleted() 

      } 

      return Disposables.create() 

     } 

    } 

    func asycTset2(value: String) -> Observable<String> { 

     return Observable<String>.create { 

      (o: AnyObserver<String>) -> Disposable in 

      DispatchQueue.main.asyncAfter(deadline: .now() + 1) { 

       o.onNext("\(value) - done 2") 

       o.onCompleted() 

      } 

      return Disposables.create() 

     } 

    } 

} 

class ViewController: UIViewController { 

    let disposeBag = DisposeBag() 

    let observer = AsyncObject() 

    // MARK: Init Methods 

    override func viewDidLoad() { 

     super.viewDidLoad() 

     self.observer.asyncTest1() 
     .flatMap { self.observer.asycTset2(value: $0) } 
     .subscribe { print($0) } 
     .addDisposableTo(disposeBag) 

    } 

} 

回答

0

得到幫助從RxSwift鬆弛@sergdot,

let test1 = self.observer.asyncTest1().shareReplay(1) 

let test2 = test1.flatMap { self.observer.asycTset2(value: $0) } 

Observable.of(test1, test2).merge().subscribe { 

    print($0) 

} 

let test1 = self.observer.asyncTest1().shareReplay(1) 

let test2 = test1.flatMap { self.observer.asycTset2(value: $0) } 

test1.concat(test2).subscribe { 

    print($0) 

} 
2

我認爲你可以與原來的合併本,以達到預期的結果。所以它應該看起來像這樣

let test1 = self.observer.asyncTest1() 
let test2 = test1.flatMap { self.observer.asyncTest2() } 

Observable 
    .of(test1, test2) 
    .merge() 
    .subscribe { print($0) } 
    .addDisposableTo(disposeBag) 
+0

很酷,太棒了!這正是我想要的! – PatrickSCLin

+0

與 有什麼區別test1.concat(test2).subscribe {print($ 0)} .addDisposableTo(disposeBag) – PatrickSCLin

+0

哪個更好? – PatrickSCLin