小编典典

Swift 将 Observable<T> 映射到 Observable<T>

all

我对将 RxSwift Observable 转换为 Observable 感到困惑

我有这样的网络功能:

func createOrder(request: AcquirebatchOrder) -> Observable<AcquirebatchOrderResult> {
    //Do networking stuff and will return with Observable<AcquirebatchOrderResult>
}

我可以这样调用该函数:

transferService.createOrder(request: request)

而且我需要将 Observable 转换为 Observable 因为我不想使用不同的参数复制 observeResultForShowUI。我试过这个但失败了:

let observableResult = transferService.createOrder(request: request).map {
acquirebatchOrderResult -> Observable<TransferSubmitResult> in
            let transferSubmitResult = TransferSubmitResult()
            //Doing something to convert data from acquirebatchOrderResult to transferSubmitResult
            Observable.just(transferSubmitResult)
}

observeResultForShowUI(result: observableResult)

private func observeResultForShowUI(result: Observable<TransferSubmitResult>) {
   result.subscribe { [weak self] (result: TransferSubmitResult) in
        //Do something with data
   } onError: { (error: Error) in
        //Handle error
   }
}

将 observableResult 传递给函数 observeResultForShowUI 时显示的错误

Cannot convert value of type ‘Observable>‘ to expected argument type ‘Observable

谢谢


阅读 73

收藏
2022-07-13

共1个答案

小编典典

你在不必要地嵌套东西。

要从 using 转到Observable<A>using Observable<B>map您需要给它一个 type 的函数(A) -> B

你所做的是给它一个函数(AcquirebatchOrderResult) -> Observable<TransferSubmitResult>(所以你的“B”是Observable<TransferSubmitResult>)。因此,您的结果最终为Observable<<Observable<TransferSubmitResult>>

所有你需要的是:

let observableResult = transferService
    .createOrder(request: request)
    .map { _ in TransferSubmitResult() }

虽然奇怪的是你TransferSubmitResult根本不使用acquirebatchOrderResult

2022-07-13