Skip to content

Instantly share code, notes, and snippets.

@r-plus
Last active August 15, 2017 14:13
Show Gist options
  • Save r-plus/3eb5d5d8b8c3140586c1dd46ec6c62fe to your computer and use it in GitHub Desktop.
Save r-plus/3eb5d5d8b8c3140586c1dd46ec6c62fe to your computer and use it in GitHub Desktop.
Migration to RxSwift from Promise: 基本編

Migration to RxSwift from Promise: 基本編

普通のタスクを代替するやり方。 fulfillをonNext+onCompleted rejectをonError にして.successをflatMap(チェーンの最後ならsubscribe)にすれば良い

    func stringTask(_ isSuccess: Bool) -> Observable<String> {
        return Observable<String>.create({ (observer) -> Disposable in
            print("start task", Date())
            DispatchQueue.global().asyncAfter(deadline: .now() + 1.0) {
                guard isSuccess else {
                    observer.onError(Err.some)
                    return
                }
                observer.onNext("val")
                observer.onCompleted()
            }
            return Disposables.create()
        })
    }
    
    let initialTask = Observable<Void>.just(())
    initialTask.flatMap { (_) -> Observable<String> in
        let successTask =  stringTask(true)
        return successTask
    }.subscribe(onNext: { (val) in
        print("finish \(val)", Date())
    }, onError: { (err) in
        print("err=\(err)")
    })
start task 2017-08-15 14:08:44 +0000
finish val 2017-08-15 14:08:45 +0000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment