MCHttpRxExtension.swift 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. //
  2. // MCHttpRxExtension.swift
  3. // HCQuanfangtong
  4. //
  5. // Created by Apple on 2021/12/24.
  6. // Copyright © 2021 Jyp. All rights reserved.
  7. //
  8. import Foundation
  9. import RxSwift
  10. import RxCocoa
  11. import RxAlamofire
  12. import Alamofire
  13. import HandyJSON
  14. extension Observable{
  15. func on(success: @escaping ((Element)->Void), error: @escaping (MCHttpResponseError<Any>)->Void) -> Disposable{
  16. return subscribe(onNext: { e in
  17. success(e)
  18. }, onError: {e in
  19. let model = MCHttpResponseError<Any>(data: nil, msg: nil, status: .error, code: nil)
  20. Mirror(reflecting: e).children.forEach { (child) in
  21. if let key = child.label{
  22. if key == "data"{
  23. model.data = child.value
  24. }
  25. if key == "msg"{
  26. model.msg = child.value as? String
  27. }
  28. if key == "status"{
  29. model.status = child.value as! MCHttpStatus
  30. }
  31. if key == "code"{
  32. model.code = child.value as? Int
  33. }
  34. }
  35. }
  36. error(model)
  37. })
  38. }
  39. }
  40. extension AnyObserver{
  41. /// 观察者
  42. /// - Parameters:
  43. /// - success: 成功
  44. /// - error: 失败
  45. /// - beforeAspect: 面向切面 - before
  46. /// - afterAspect: 面向切面 - after
  47. /// - Returns: 观察者
  48. static func create(success: @escaping ((Element)->Void), error: @escaping (MCHttpResponseError<Any>)->Void, beforeAspect: @escaping (()->Void) = {}, afterAspect: @escaping (()->Void) = {}) -> AnyObserver<Element>{
  49. return AnyObserver.init {(event) in
  50. switch event{
  51. case .next(let e):
  52. beforeAspect()
  53. success(e)
  54. afterAspect()
  55. case .error(let e):
  56. beforeAspect()
  57. let model = MCHttpResponseError<Any>(data: nil, msg: nil, status: .error, code: nil)
  58. Mirror(reflecting: e).children.forEach { (child) in
  59. if let key = child.label{
  60. if key == "data"{
  61. model.data = child.value
  62. }
  63. if key == "msg"{
  64. model.msg = child.value as? String
  65. }
  66. if key == "status"{
  67. model.status = child.value as! MCHttpStatus
  68. }
  69. if key == "code"{
  70. model.code = child.value as? Int
  71. }
  72. }
  73. }
  74. error(model)
  75. afterAspect()
  76. case .completed: break
  77. }
  78. }
  79. }
  80. }