Skip to content

Instantly share code, notes, and snippets.

@danielt1263
Created August 13, 2020 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielt1263/864e194a6845f1deb98f48e9de594559 to your computer and use it in GitHub Desktop.
Save danielt1263/864e194a6845f1deb98f48e9de594559 to your computer and use it in GitHub Desktop.
Gather up errors into a single Observable<Error>
//
// ErrorRouter.swift
//
// Created by Daniel Tartaglia on 5/23/20.
// Copyright © 2020 Daniel Tartaglia. MIT License.
//
import Foundation
import RxCocoa
import RxSwift
/// Reroutes errors out of the strream they were emitted from and into itself as a next event.
final class ErrorRouter: SharedSequenceConvertibleType {
typealias SharingStrategy = DriverSharingStrategy
private let _subject = PublishSubject<Error>()
func rerouteError<O: ObservableConvertibleType>(from source: O) -> Observable<O.Element> {
return source.asObservable()
.catchError { [_subject] error in
_subject.onNext(error)
return Observable.empty()
}
}
func asSharedSequence() -> SharedSequence<SharingStrategy, Error> {
return _subject.asObservable().asDriver(onErrorRecover: { _ in Driver.empty() })
}
func asObservable() -> Observable<Error> {
return _subject.asObservable()
}
deinit {
_subject.onCompleted()
}
}
extension ObservableConvertibleType {
/// Absorbes errors and routes them to the error router instead. If the source emits an error, this operator will emit a completed event and the error router will emit the error as a next event.
/// - Parameter errorRouter: The error router that will accept the error.
/// - Returns: The source observable's events with an error event converted to a completed event.
func rerouteError(_ errorRouter: ErrorRouter) -> Observable<Element> {
return errorRouter.rerouteError(from: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment