RxSwiftCommunity / RxSwiftExt

A collection of Rx operators & tools not found in the core RxSwift distribution
MIT License
1.33k stars 213 forks source link

Add `mapToResult` Operator #249

Closed Woollim closed 4 years ago

Woollim commented 4 years ago

Hello đź‘‹
I want to add mapToResult operator mapToResult operator is transform Observable’s event (Element, Error) to element of Result<Element, Error> If we use Result as Observable’s Element, we can solve two problems.

Problem 1 The type of error emitted by Observable is Swift.Error. Therefore, we add unnecessary error statements. ex) case default

Solution 1 Result can specify that Observable only emits certain error type. So we don’t have to add unnecessary error statements.

Problem 1 When emitted error by Observable, that was died (even HotObservable)

// `requestButtonTapped` is HotObservable
// `weatherInfo` dies when `requestWeatherInfo` stream emit Error
let weatherInfo = requestButtonTapped
  .flatMapLatest { NetworkAPI.requestWeatherInfo() }
  .share()  

Solution 2 If Observable emit Result.failure instead of error, we can deal with errors without completion of Observable.

// `requestButtonTapped` is HotObservable
// `weatherInfo` never die when `requestWeatherInfo` stream emit Error
let weatherInfo = requestButtonTapped
  .flatMapLatest {
    NetworkAPI.requestWeatherInfo().mapToResult(~)
  }
  .do(onNext: { result in
    if case .failure(let error) = result {
        Log(error)
    }
  })
  .share()  

Many Library use Result (Alamofire, Maya, Combine…), so I’m sure mapToResult Operator will be very useful in RxSwift. Give me your useful opinion, Thanks you.

rxswiftcommunity[bot] commented 4 years ago
Warnings
:warning: It looks like code was changed without adding anything to the Changelog. If this is a trivial PR that doesn't need a changelog, add #trivial to the PR title or body.

Generated by :no_entry_sign: dangerJS