RxSwift:Chain Completable to Observable

RxSwift: Chain Completable to Observable

我想将一个 Completable 链接到一个可观察元素。调用 flatMap 后,订阅时似乎没有调用 onCompleted 和 onError 回调。

var user = PublishRelay<User>()

func fetchUserInformation(_ userId: String) -> Completable {
    return Completable.create { observer in
        apiService.fetchInformation(for: userId, completion: { response in
            if let name = response?.name {
                user.accept(User(name: name))
                observer(.completed)
            } else {
                observer(.error(ServiceError.userInformation))
            }
        })
        return Disposables.create()
    }
}

login()
.flatMap{ userId in fetchUserInformation(userId) }
.subscribe(
    onCompleted: {
        print("Success!") // Not being called at all
    },
    onError: { error in
        print(error)  // Not being called at all
    }
).disposed(by: disposeBag)

虽然正在调用fetchUserInformationobserver(.completed)并且正在成功获取用户信息,但我将无法在订阅时捕获 onCompleted(仅当前面有 flatMap 时)。

有没有一个干净的方法来实现这个?

Already tried .materialized() just after the flatMap call in order to get an

    Observable<Event<Never>>

rather than a

    Observable<Never>

It doesn't work either.

据我所知,您不能将 Completable 转换为 Observable,因为后者会省略值,而 Completable 不会。

我猜 flatMap 正在从登录返回 Observables,然后你将它转换为 Completables,这就是它失败的原因

我认为你可以这样做:

login()
    .flatMap{ userId -> Observable<Void> in
        return fetchUserInformation(userId).andThen(.just(Void()))
    }.subscribe(onNext: { _ in
        ...
    }).disposed(by: disposeBag)

正确的解决方案是使用“andThen”运算符。

someCompletable
   .andThen(someObservable) 

编辑: 只需阅读您的其余代码 - 我完全不确定您为什么使用 Completable 因为看起来您实际上是从该流返回一些元素。

您可能希望使用 Single 或 Plain-ol' observable 来中继该值,而无需使用外部中继。