gpt4 book ai didi

ios - Observable.empty 在 zip 中返回什么?

转载 作者:行者123 更新时间:2023-11-28 10:14:27 25 4
gpt4 key购买 nike

如果一个函数返回一个 Observable.empty(),那么在执行这个值的 Observable.zip 之后我会得到什么?问题是我总是想执行 Observable.zip 中的代码,并且由于 source2() 可能会失败,所以我执行了一个 catchError 然后返回一个空的可观察对象。但我不确定 zip 是否仍会使用这种方法调用 block 。

 func source1() -> Observable<String> {
return Observable.just("test")
}

func source2() -> Observable<Int> {
return anObservableThatCanFail()
.catchError { error -> Observable<Int>
return Observable.empty()
}
}

func myFunc() {
Observable.zip(source1(), source2()) { string, integer
//this will be called despite source2() do a empty()?
//and if so, what integer contains?
}

最佳答案

来自 reactivex.io的文档:

It applies this function in strict sequence, so the first item emitted by the new Observable will be the result of the function applied to the first item emitted by Observable #1 and the first item emitted by Observable #2; the second item emitted by the new zip-Observable will be the result of the function applied to the second item emitted by Observable #1 and the second item emitted by Observable #2; and so forth. It will only emit as many items as the number of items emitted by the source Observable that emits the fewest items.

所以在这种情况下,因为 .empty()将发出 0 项,意思是 zip也会发出 0 项。

如果你真的需要执行压缩功能,你可以改变source2()的类型来自 Observable<Int>Observable<Int?>并且,而不是返回 .empty()来自 catchError阻止,返回 .just(nil) .

func source2() -> Observable<Int?> {
return anObservableThatCanFail()
.map { (result: Int) -> Int? in result }
.catchError { error -> Observable<Int?>
return Observable.just(nil)
}
}

关于ios - Observable.empty 在 zip 中返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43065527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com