Kotlin 的 zip 方法中用作参数的 Observable 数量似乎有限制。如果这是准确的,最好的选择是什么?
例如,当我使用 9 个参数时,它会按预期工作。当我添加第十个参数时,我收到错误无法推断此参数的类型。请明确指定
Observable.zip(
//TODO: parameterize exchange symbols based on pair
methodOne() as Observable<Any>),
methodTwo() as Observable<Any>),
methodThree() as Observable<Any>),
methodFour() as Observable<Any>),
methodFive() as Observable<Any>),
methodSix() as Observable<Any>),
methodSeven() as Observable<Any>),
methodEight() as Observable<Any>),
methodNine() as Observable<Any>),
{ oneResult, twoResult, threeResult, fourResult, fiveResult, sixResult, sevenResult, eightResult, nineResult ->
//logic here applying computation to results
})
.subscribe(
{},
{
println(String.format("Error: %s", it.message))
})
.unsubscribe()
}
最佳答案
RxJava 仅支持最多 9 个不同的源, zip
。除此之外,您必须使用 zip(Iterable<ObservableSource>, Func<Object[],R>)
方法并强制转换 Object[]
的每个元素返回到其各自的类型。
Returns an
Observable
that emits the results of a specifiedcombiner
function applied to combinations of items emitted, in sequence, by anIterable
of otherObservableSource
s. zip applies this function in strict sequence, so the first item emitted by the newObservableSource
will be the result of the function applied to the first item emitted by each of the sourceObservableSource
s; the second item emitted by the newObservableSource
will be the result of the function applied to the second item emitted by each of thoseObservableSource
s; and so forth.The resulting
ObservableSource<R>
returned from zip will invokeonNext
as many times as the number ofonNext
invocations of the sourceObservableSource
that emits the fewest items.The operator subscribes to its sources in order they are specified and completes eagerly if one of the sources is shorter than the rest while disposing the other sources. Therefore, it is possible those other sources will never be able to run to completion (and thus not calling
doOnComplete()
). This can also happen if the sources are exactly the same length; if source A completes and B has been consumed and is about to complete, the operator detects A won't be sending further values and it will dispose B immediately. For example:zip(Arrays.asList(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2)), (a) -> a)
action1
will be called butaction2
won't. To work around this termination property, usedoOnDispose(Action)
as well or useusing()
to do cleanup in case of completion or adispose()
call. Note on method signature: since Java doesn't allow creating a generic array with newT[]
, the implementation of this operator has to create anObject[]
instead. Unfortunately, aFunction<Integer[], R>
passed to the method would trigger aClassCastException
.
关于java - .zip 方法中的 Observable 数量是否有限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50937317/