RxSwift URLSession请求被处置

时间:2019-07-01 08:54:19

标签: swift rx-swift

我正在学习使用RxSwift,但是我一直在使用此简单代码。我的意图是采用一个APIRequest类型,就像这样简单:

preferences

将其传递给API客户端,最后返回类型为public protocol APIRequest: Encodable { associatedtype Response: Decodable var path: String { get } } 的Observable,但是,我一直在控制台中看到T.Response的状态:

cancelled

这是我的APIClient的代码:

2019-07-01 10:46:04.847: test api request -> subscribed
2019-07-01 10:46:04.855: test api request -> isDisposed

我一直试图通过以下方式将结果打印到控制台上

func send<T: APIRequest>(_ request: T) -> Observable<T.Response> {
    guard let fullURL = endpoint(for: request) else {
        return Observable.error(APIError.invalidBaseURL)
    }

    return Observable<T.Response>.create { observer in
        let request = URLRequest(url: fullURL)
        let response = URLSession.shared.rx.response(request: request)
                              .debug("test api request")

        return response.subscribe(onNext: { response, data in
            if 200..<300 ~= response.statusCode {
                guard let responseItems = try? self.jsonDecoder.decode(T.Response.self, from: data) else {
                    return observer.onError(APIError.decodingFailed)
                }

                observer.onNext(responseItems)
                observer.onCompleted()
            }
        }, onError: { error in
            observer.onError(APIError.other(error))
        }, onCompleted: nil,
           onDisposed: nil)
    }
}

我在做什么错,为什么?

1 个答案:

答案 0 :(得分:2)

我尝试重新创建您的代码,但在我的设备上似乎可以正常工作

func send<T>(_ request: T) -> Observable<Data> {

    let request = URLRequest(url: URL(string: "sdf")!)

    return Observable.create { obs in
        URLSession.shared.rx.response(request: request).debug("r").subscribe(
            onNext: { response in
                return obs.onNext(response.data)
        },
            onError: {error in
                obs.onError(error)
        })
    }
}

我正在订阅它,它会产生错误

send("qwe").subscribe(
            onNext: { ev in
            print(ev)
        }, onError: { error in
            print(error)
        }).disposed(by: disposeBag)