Handling Network error in combination with binding to tableView (Moya, RxSwift, RxCocoa)

前端 未结 2 680
栀梦
栀梦 2021-02-08 22:17

I am currently using Moya to make my network requests. I have implemented the following from one of the example projects @ https://github.com/DroidsOnRoids/RxSwiftExamples#tutor

相关标签:
2条回答
  • 2021-02-08 22:32

    I personally handle network errors in services that make/parse network requests. Good way to do that would be to wrap your network results in some kind of enum (similar to optional, but with error if nil). So you would have something like:

    enum APIResult<T> {
        case Success(T)
        case Error(ErrorType)
    }
    

    And then your services would return something like this

    Observable<APIResult<[Restaurant]>>
    

    If you use MVVM architecture you would then filter only successful results in view model and provide that data to view controller.

    Also you should take a look at Driver unit. It is unit that is specifically made for UI bindings, so it subscribes on Main thread only, never errors and shares last result.

    To translate Observable to Driver you use one of the three methods:

    func asDriver(onErrorJustReturn onErrorJustReturn: Self.E) -> RxCocoa.Driver<Self.E>
    func asDriver(onErrorDriveWith onErrorDriveWith: RxCocoa.Driver<Self.E>) -> RxCocoa.Driver<Self.E>
    func asDriver(onErrorRecover onErrorRecover: (error: ErrorType) -> RxCocoa.Driver<Self.E>) -> RxCocoa.Driver<Self.E>
    

    This approach would automatically deal with your second question, because when Observable emits an error, all subscribers unsubscribe, ie. it terminates the stream. Try to put .debug() behind your api.restaurants() call and see by yourself that it unsubscribes.

    You can read more about Driver and other units here

    0 讨论(0)
  • 2021-02-08 22:45

    Just add catchErrorJustReturn([]) before binding your table.

    0 讨论(0)
提交回复
热议问题