PatrickSCLin PatrickSCLin - 9 days ago 6
Swift Question

RXSwift simple async example?

I'm new in RXSwift, I just try to implement a simple async example

but subscribe will never be called.

What I miss ?

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 ======================

I'm trying to do something more advanced, a chain which allow pass value from previous, but the result was not expected. what I miss ?

output was


next(done 1 - done 2)


what I expected was


next(done 1)

next(done 1 - done 2)

completed


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)

}

}

Answer

I think you can merge this with the original one, to achieve the expected result. So it should look something like this

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

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