Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava Zip Observable Iterables

I want to zip a list of Observable<List<Int>>.

fun testObservablezip() {
    val jobs = mutableListOf<Observable<List<Int>>>()
    for (i in 0 until 100 step 10) {
        val job = Observable.fromArray(listOf(i + 1, i + 2, i + 3))
        jobs.add(job)
    }

    val listMerger = Function<Array<List<Int>>, List<Int>> { it.flatMap { it } }
    Observable.zip(jobs, listMerger) // No valid function parameters
}

Even though the listMerger has its input and output defined, zip does not accept it.

like image 883
Steven Lang Avatar asked May 19 '18 09:05

Steven Lang


1 Answers

zip's function is defined in RxJava as Function<? super Object[], R> so you have to specify an object array, not a List<Int> array and then cast the object array elements back to List<Int>:

import io.reactivex.Observable
import io.reactivex.functions.Function;

fun testObservablezip() {
    val jobs = mutableListOf<Observable<List<Int>>>()
    for (i in 0 until 100 step 10) {
        val job = Observable.fromArray(listOf(i + 1, i + 2, i + 3))
        jobs.add(job)
    }

    val listMerger = Function<Array<Any>, List<Int>> { 
         it.flatMap { it as List<Int> } }

    Observable.zip(jobs, listMerger) // No valid function parameters
}
like image 70
akarnokd Avatar answered Sep 20 '22 08:09

akarnokd