Last active
January 27, 2019 15:54
-
-
Save creaaa/88144506f022ec5b0716b8342ff145ab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Q1] | |
let single = Single<Int>.create(subscribe: { (observer) in | |
observer(.success(1)) | |
observer(.success(2)) | |
return Disposables.create() | |
}) | |
_ = single.subscribe(onSuccess: { print($0) }, | |
onError: { print($0) }) | |
// 1 | |
[Q2] | |
let single = Single<Int>.create(subscribe: { (observer) in | |
observer(.success(1)) | |
observer(.success(2)) | |
return Disposables.create() | |
}) | |
_ = single.subscribe(onSuccess: { print($0) }, | |
onError: { print($0) }) | |
// 1 | |
[Q3] | |
let single = Single<Int>.create(subscribe: { (observer) in | |
observer(.success(1)) | |
return Disposables.create() | |
}) | |
.flatMap { _ in Single.just(2) } | |
.flatMap { _ in Single<MyError>.just(MyError()) } // あ、これは MyError型のElement を onSuccessで流していて、onErrorではないのか...!! | |
.flatMap { _ in Single.just(3) } | |
_ = single.subscribe(onSuccess: { print($0) }, | |
onError: { print($0) }) | |
// 3 | |
[Q4] | |
let single = Single<Int>.create { singleEvent in | |
singleEvent(.success(1)) | |
return Disposables.create() | |
} | |
.flatMap { value in | |
return Single<Int>.create { singleEvent in | |
singleEvent(.success(value + 1)) | |
return Disposables.create() | |
} | |
} | |
.flatMap { value in | |
return Single<Int>.create { singleEvent in | |
singleEvent(.error(MyError())) | |
return Disposables.create() | |
} | |
} | |
.flatMap { value in | |
return Single<Int>.create { singleEvent in | |
singleEvent(.success(value * 2)) | |
return Disposables.create() | |
} | |
} | |
} | |
_ = single.subscribe(onSuccess: { print($0) }, | |
onError: { print($0) }) | |
// MyError() | |
この場合は、途中で完全に onErrorが流れているので、subscribe元までエラーが伝播し、かつそれより後の値(3)は無視される。 | |
だがそもそもこの「エラーは伝播する」という挙動、なにもSingleに限ったことじゃないのだ。 | |
let observable = Observable<Int>.create { observer in | |
observer.onNext(1) | |
return Disposables.create() | |
} | |
.flatMap { _ in Observable.just(2) } | |
.flatMap { _ in | |
return Observable<Int>.create { observer in | |
observer.onError(MyError()) | |
return Disposables.create() | |
} | |
} | |
.flatMap { _ in Observable.just(3) } | |
_ = observable.subscribe(onNext: { print($0) }, | |
onError: { print($0) }) | |
// MyError() | |
はい、そういうこと。エラーはsubscribe元に伝播する。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment