Home Articles

RxSwift:在Alamofire返回数据之前激活onDisposed

Asked
Viewed 1642 times
3

我正在尝试使用rxSwift和Alamofire从REST(swift 2.3)获取JSON数据 . 这是我的代码:

func getArticles(articlesReq: ArticlesReq) - > Observable < [Article] > {
      return Observable < [Article] > .create {
          observer in
              let request = Alamofire.request(.POST, apiPath, parameters: DataHelper().convertStringToDictionary(JSONString), encoding: .JSON)
                  .responseArray {
                      (response: Response < [Article], NSError > ) in
                          if let articlesArray = response.result.value {
                              observer.on(.Next(articlesArray))
                          }
                          observer.on(.Completed)
                  }
          return AnonymousDisposable {
              request.cancel()
          }

      }

  }

  getArticles(articlesReq).observeOn(MainScheduler.instance)
      .subscribe(
          onNext: {
              data in
              print(data)
          },
          onError: {
              error in
              print(error)
          },
          onCompleted: {
              print("Completed")
          },
          onDisposed: {
              print("Disposed")
          }
      ).addDisposableTo(db)

在Alamofire.request返回数据之前的onDisposed返回数据(onNext,onError,onCompleted不返回数据) . 如何等待回复?

1 Answer

  • 1

    尽量保持对 disposbag 的强烈引用,如下所示:

    let disposeBag = DisposeBag()
    
    func setupRx() {
    
      getArticles(articlesReq).observeOn(MainScheduler.instance)
          .subscribe(onNext: {
              print("onNext")
            // ... use $0 parameter
          }, onError: {
              print("onError")
            // ... use $0 parameter
          }, onCompleted: { 
              print("onCompelete")
          }, onDisposed: nil)
      .addDisposableTo(disposeBag)
    
    }
    

    你的 disposeBag 应该比响应活得更久 .

    希望这可能有所帮助 .

Related