Description
I wanted to use the version of combineLatest
that takes an array/iterable. The only problem is that it gives you a Array<Any>
which wasn't very useful. I thought it was kind of weird that RxJava doesn't have a version that gives you Array<T>
. Was this because of the Java compiler couldn't figure out the two overloads? Anyway, would we want to provide a version in this project that correctly has the type T
for the array? Maybe there is a good reason not to, but I found it really useful for what I was working on.
I made one myself by using both Kotlin and Java together to do what I think is the most efficient version while still being useful.
inline fun <reified T: Any,R> Observables.combineLatest(observables: Array<Observable<T>>,
crossinline combiner: (Array<T>) -> R)
: Observable<R> =
Observable.combineLatest(
observables,
{ items -> combiner.invoke(ArrayUtils.cast(items, arrayOfNulls<T>(items.size))) },
Observable.bufferSize())
@NotNull
public static <T> T[] cast(@NotNull Object[] items,
@NotNull T[] ts) {
return Arrays.asList(items).toArray(ts);
}
This uses Kotlin to actually create the array we are copying to. We can do this because the type is reified. The java then uses the Arrays.asList
to create a simple list wrapper for the array and then copies it into the array we made. So we make one copy of the array and a list wrapper for the array.