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

耗尽温柔 提交于 2019-12-03 06:46:05

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!