Single+Response.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import Foundation
  2. import RxSwift
  3. #if !COCOAPODS
  4. import Moya
  5. #endif
  6. #if canImport(UIKit)
  7. import UIKit.UIImage
  8. #elseif canImport(AppKit)
  9. import AppKit.NSImage
  10. #endif
  11. /// Extension for processing raw NSData generated by network access.
  12. public extension PrimitiveSequence where Trait == SingleTrait, Element == Response {
  13. /// Filters out responses that don't fall within the given closed range, generating errors when others are encountered.
  14. func filter<R: RangeExpression>(statusCodes: R) -> Single<Element> where R.Bound == Int {
  15. flatMap { .just(try $0.filter(statusCodes: statusCodes)) }
  16. }
  17. /// Filters out responses that have the specified `statusCode`.
  18. func filter(statusCode: Int) -> Single<Element> {
  19. flatMap { .just(try $0.filter(statusCode: statusCode)) }
  20. }
  21. /// Filters out responses where `statusCode` falls within the range 200 - 299.
  22. func filterSuccessfulStatusCodes() -> Single<Element> {
  23. flatMap { .just(try $0.filterSuccessfulStatusCodes()) }
  24. }
  25. /// Filters out responses where `statusCode` falls within the range 200 - 399
  26. func filterSuccessfulStatusAndRedirectCodes() -> Single<Element> {
  27. flatMap { .just(try $0.filterSuccessfulStatusAndRedirectCodes()) }
  28. }
  29. /// Maps data received from the signal into an Image. If the conversion fails, the signal errors.
  30. func mapImage() -> Single<Image> {
  31. flatMap { .just(try $0.mapImage()) }
  32. }
  33. /// Maps data received from the signal into a JSON object. If the conversion fails, the signal errors.
  34. func mapJSON(failsOnEmptyData: Bool = true) -> Single<Any> {
  35. flatMap { .just(try $0.mapJSON(failsOnEmptyData: failsOnEmptyData)) }
  36. }
  37. /// Maps received data at key path into a String. If the conversion fails, the signal errors.
  38. func mapString(atKeyPath keyPath: String? = nil) -> Single<String> {
  39. flatMap { .just(try $0.mapString(atKeyPath: keyPath)) }
  40. }
  41. /// Maps received data at key path into a Decodable object. If the conversion fails, the signal errors.
  42. func map<D: Decodable>(_ type: D.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder(), failsOnEmptyData: Bool = true) -> Single<D> {
  43. flatMap { .just(try $0.map(type, atKeyPath: keyPath, using: decoder, failsOnEmptyData: failsOnEmptyData)) }
  44. }
  45. }