Observable.empty 什么 returns 压缩包里面?

Observable.empty what returns inside a zip?

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

 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?>,而不是 returning .empty() 来自 catchError 块,return .just(nil).

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