Created
August 11, 2016 22:43
-
-
Save mingyeow/68a65163cc78c35a09b8de386799be6e to your computer and use it in GitHub Desktop.
ObservableType+KeepCalmAndCarryOn.swift
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
// In RXSWIFT, the flatmap has to handle the error by passing on observable, otherwise future signals will not trigger it. See examples below. | |
// This means that we often need to bundle the result in an optional or result type, and handle it in the flatmap catcherror | |
enum AwfulError: ErrorType { case Bad} | |
func rxFunction(arg:Int) -> Observable<Int>{ | |
let k = Observable<Int>.create({ observer -> Disposable in | |
observer.onNext(arg * 2) | |
observer.onError(AwfulError.Bad) | |
return NopDisposable.instance | |
}) | |
return k | |
} | |
var l = [1, 2, 3].toObservable() | |
// KEEP CALM -> 2, 4, 6 | |
l.flatMapLatest { i in | |
return rxFunction(i).keepCalmAndCarryOn{ print ($0) } | |
}.subscribeNext{ i in print("RESULT (KEEP CALM): \(i)") } | |
// NO HANDLING -> 2, <END> | |
l.flatMapLatest { i in | |
return rxFunction(i) | |
}.subscribeNext{ i in print("RESULT (NO HANDLING): \(i)") } | |
// JUST RETURN -> 2, 0, 4, 0, 6, 0 <END> | |
var feedRxJustReturn = l.flatMapLatest { i in | |
return rxFunction(i) | |
}.subscribeNext{ i in print("RESULT (JUST RETURN): \(i)") } | |
// CATCH -> // 2, 1, 4, 1, 6, 1 | |
var feedRxHandleError = l.flatMapLatest { i in | |
return rxFunction(i).catchError({ e in | |
print (e) | |
return Observable.just(1) | |
}) | |
}.subscribeNext{ i in print("RESULT (HANDLE ERROR): \(i)")} | |
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
import RxSwift | |
import Foundation | |
// to be used mostly in flatmap, where you want to handle the error seperately | |
extension ObservableType { | |
func keepCalmAndCarryOn(errorHandler:(ErrorType -> Void)) -> Observable<E>{ | |
return Observable<E>.create{ observer -> Disposable in | |
self.subscribe( | |
onNext: { observer.onNext($0)}, | |
onError: { errorHandler($0); observer.onCompleted()}, | |
onCompleted: {observer.onCompleted()} | |
) | |
return NopDisposable.instance | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment