Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How about implement Moya-Decodable ? #140

Open
Arcovv opened this issue Feb 22, 2017 · 1 comment
Open

How about implement Moya-Decodable ? #140

Arcovv opened this issue Feb 22, 2017 · 1 comment

Comments

@Arcovv
Copy link

Arcovv commented Feb 22, 2017

Recently, I try to use RxSwift + Moya + Decodable to do my project. But I can't find a better Decodable extension for supporting Moya.

So I try to inplement it by myself.

Perhaps it should be written in other better ways, such as naming can have a better way. I'm not sure:

import Foundation
import Moya
import RxSwift
import Decodable

extension ObservableType where E == Response {
  
  public func mapObject<T: Decodable>(type: T.Type) -> Observable<T> {
    return flatMap { response -> Observable<T> in
      return Observable.just(try response.mapObject())
    }
  }
  
  public func mapObjectArray<T: Decodable>(type: T.Type) -> Observable<[T]> {
    return flatMap { response -> Observable<[T]> in
      return Observable.just(try response.mapObjectArray())
    }
  }
  
}

extension Moya.Response {

  public func mapObject<T: Decodable>() throws -> T {
    return try T.decode(try mapJSON())
  }
  
  public func mapObjectArray<T: Decodable>() throws -> [T] {
    return try [T].decode(try mapJSON())
  }
  
}

So it can use like this:

let provider = RxMoyaProvider<Api>()
provider.request(.requestSomething)
  .mapObject(type: DecodableObject.self)
  .subscribe { event in
    switch event {
    case .next(let element):
      print("next: \(element)")
    case .error(let error):
      print("error: \(error)")
    case .completed:
      print("completed")
    }
  }
  .addDisposableTo(disposeBag)
@Arcovv
Copy link
Author

Arcovv commented Feb 22, 2017

I forgot to add rootKey: String = nil for every methods...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant