RxSwift: Better Error Handling With CompactMap
Use one of RxSwift 5’s newest features to streamline your code.
Study RxSwift long enough, say, a week or so, and you’re bound to run across some variant of the following code:
class NoErrorViewModel { var data: Observable<[String]>!
var dataService = DataService() init(load: Observable<Void>) {
data = load
.flatMapLatest { [unowned self] _ in
self.dataService.load()
.catchErrorJustReturn([])
}
.observeOn(MainScheduler.instance)
.share()
}}
Here we want to return an array of strings from our data service every time a load event occurs. Say, on every viewWillAppear().
So, we use flatMapLatest() to wrap our asynchronous API call into an observable, share() the result just to make sure multiple subscriptions to data don’t trigger multiple API calls for the same event, and then assign the result to our view model’s data observable back on the main thread so we can update our UI. All well and good.
However, in order to keep our event stream alive we need to catch any errors that might occur. If we don’t, and we let an error escape from our…