Last active
April 13, 2017 07:57
RxSwiftのSingleを使ったサンプル。Singleは性質上、データを一回しか流さないのでflatMapを使う。valueが取得できた場合はvalueを返す。errorが取得できた場合はそのエラーを後ろに伝播させていき、それ以降の処理を無視する。
This file contains hidden or 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
enum SomeError: Error { | |
case a | |
} | |
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(SomeError.a)) | |
return Disposables.create() | |
} | |
}.flatMap { value in | |
return Single<Int>.create { singleEvent in | |
singleEvent(.success(value * 2)) | |
return Disposables.create() | |
} | |
} | |
let _ = single.subscribe { singleEvent in | |
print(singleEvent) | |
} | |
// error(SomeError.a) | |
// あるいは↓ | |
let _ = single.subscribe { singleEvent in | |
switch singleEvent { | |
case .success(let value): | |
print("Success: \(value)") | |
case .error(let error): | |
print("Error: \(error)") | |
} | |
} | |
// あるいはRxSwift3.4以上なら↓も可能っぽい | |
let _ = single.subscribe( | |
onSuccess: { value in | |
print("Success: \(value)") | |
}, | |
onError: { error in | |
print("Error: \(error)") | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment