RxSwift API响应

时间:2019-04-25 10:53:51

标签: swift rx-swift

如果我取消注释下面的注释代码,那么下面的代码将使我感到困惑。如果我发表评论,那是行不通的。我不知道这是什么问题:

func getMostPopularRepositories(byLanguage language: String) -> Observable<[Repository]> {
  let encodedLanguage = language.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!

  let provider = MoyaProvider<Github>(plugins: [NetworkLoggerPlugin(verbose: true)])
  let parameters = [“q”: “language:\(encodedLanguage)“,“sort”: “stars”]

  /*
  provider.rx
    .request(.repositories(parameters))
    .map([Repository].self, atKeyPath: “items”)
    .subscribe { event in
  }.dispose()
  */

  let request = provider.rx.request(.repositories(parameters)).asObservable()
  // RxSwift.(unknown context at $101ccc3e8).AnonymousObservable<Moya.Response>
  print(request)
  let pRepos = request.map([Repository].self, atKeyPath: “items”)
  // RxSwift.(unknown context at $101ccf26c).FlatMap<Moya.Response, RxSwift.Observable<Swift.Array<RepoSearcher.Repository>>>
  print(pRepos)
  return pRepos
}

2 个答案:

答案 0 :(得分:2)

我还没有和Moya合作。

但是似乎您需要.subscribe才能使.request工作。

答案 1 :(得分:0)

您需要订阅可观察的pRepos来发送网络请求,因为可观察的对象要等到观察者订阅它之后才开始发出项目,并在调用subscribe时开始将值推送给观察者。

所以就您而言

func getMostPopularRepositories(byLanguage language: String) -> Observable<[Repository]> {
    let encodedLanguage = language.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!

    let provider = MoyaProvider<Github>(plugins: [NetworkLoggerPlugin(verbose: true)])
    let parameters = [“q”: “language:\(encodedLanguage)“,“sort”: “stars”]

    let request = provider.rx.request(.repositories(parameters)).asObservable()
    // RxSwift.(unknown context at $101ccc3e8).AnonymousObservable<Moya.Response>
    print(request)
    let pRepos = request.map([Repository].self, atKeyPath: “items”)
    // RxSwift.(unknown context at $101ccf26c).FlatMap<Moya.Response, RxSwift.Observable<Swift.Array<RepoSearcher.Repository>>>
    print(pRepos)
    return pRepos
}

//订阅Observable <[Repository]>

的代码
let disposeBag = DisposeBag()
let popularReposObservable: Observable<[Repository]> =   getMostPopularRepositories(byLanguage: "English")
popularReposObservable
    .observeOn(MainScheduler.instance)
    .subscribe(onNext: { (popularRepos: [Repository]) in
        print(popularRepos)
    })
    .disposed(by: disposeBag)