RxSwift and Alamofire: can't subscribe events after alamofire handling response data

1k Views Asked by At

Here are some of my codes:

func toObservable() -> Observable<T> {
    return Observable.create {
        observer -> Disposable in
        let urlRequest = try? self.asURLRequest()

        Alamofire.request(urlRequest!)
            .responseObject{ (response: DataResponse<T>) in
                if response.result.isSuccess {
                    if let responseEntity = response.result.value {
                        if let _ = responseEntity.error {
                            observer.onError(ResponseError.generic)
                        } else {
                            observer.onNext(responseEntity)
                        }
                    } else {
                        // TODO
                    }
                } else {
                    // TODO
                }
        observer.onCompleted()

        }

        return Disposables.create()
    }
}

and when I call this function:

toObservable().subscribe(onNext: {
            print("onNext")
            // ... use $0 parameter
        }, onError: {
            print("onError")
            // ... use $0 parameter
        }, onCompleted: { 
            print("onCompelete")
        }, onDisposed: nil)
    .addDisposableTo(DisposeBag())

It just can not print anything. So any idea about this? Many thanks!

(I used AlamofireObjectMapper, RxSwift frameworks)

Same question are here but nobody answered.

2

There are 2 best solutions below

2
On BEST ANSWER

Try to keep a strong reference to disposbag like this:

let disposeBag = DisposeBag()

func setupRx() {

  toObservable()
      .debug("Alamofire.request")
      .subscribe(onNext: {
          print("onNext")
        // ... use $0 parameter
      }, onError: {
          print("onError")
        // ... use $0 parameter
      }, onCompleted: { 
          print("onCompelete")
      }, onDisposed: nil)
  .addDisposableTo(disposeBag)

}

And you can use debug operator to see what happened.

Hope this may help.

0
On
let disposeBag = DisposeBag()

addDisposable was deprecated..

func setupRx() {

  toObservable()
      .debug("Alamofire.request")
      .subscribe(onNext: {
          print("onNext")
        // ... use $0 parameter
      }, onError: {
          print("onError")
        // ... use $0 parameter
      }, onCompleted: { 
          print("onCompelete")
      }, onCompleted: {
        print("onCompelete")
        }).disposed(by: disposeBag)

}