swiftrx-swiftrxalamofire

Created observable doesn't emit anything


I'm trying to create a function which returns Observable<(HTTPURLResponse, Any)> using RxAlamofire:

class APIManager {
    let disposeBag = DisposeBag()
    func getResponse(credentialData: Credentials, ulr: String)->Observable<(HTTPURLResponse, Any)>{
    let credentialData = "\(credentialData.username):\(credentialData.password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
    let base64Credentials = credentialData.base64EncodedString()
    let headers = ("Authorization", "Basic \(base64Credentials)")
    let header = HTTPHeaders.init(dictionaryLiteral: headers)
    return Observable.create{ observer in
        requestJSON(.get, ulr, parameters: nil, encoding: JSONEncoding.default, headers: header)
        .subscribe(onNext: { response in
            observer.onNext(response)
            } ,


    onError: { error in
        observer.onError(error)
        },
    onCompleted: {},
    onDisposed: {}).disposed(by: self.disposeBag)
    return Disposables.create()
    }
}    

}

The code into onNext is not executed; it's going through onDisposed only.

How can I fix it?


Solution

  • Why are you wrapping requestJSON function with another Observable which is just forwarding the same element and error, when that function is already returning the Observable you need?.

    Isn't this enough for you?

    class APIManager {
        func getResponse(credentialData: Credentials, ulr: String) -> Observable<(HTTPURLResponse, Any)> {
            let credentialData = "\(credentialData.username):\(credentialData.password)"
                .data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
            let base64Credentials = credentialData.base64EncodedString()
            let headers = ("Authorization", "Basic \(base64Credentials)")
            let header = HTTPHeaders.init(dictionaryLiteral: headers)
            return requestJSON(.get, ulr, parameters: nil, encoding: JSONEncoding.default, headers: header)
        }
    }