Laufwunder
Laufwunder

Reputation: 839

RxJava: List of Singles

I got some trouble with RxJava. I am coding with Kotlin. Here is my problem:
I have a list of Singles. Now I need the emitted results of all Singles to proceed. It would be great if the Singles could run in parallel and the results stay in the same order. When all Singles emitted their result, I want to proceed.

val list_of_singles = mutableListOf<Single<Type>>()
val results: List<ResultType> = runSingles(list_of_singles)
// use results here...

Let me know if you need more information.

Thanks!!! :)

Upvotes: 1

Views: 3311

Answers (2)

David Rawson
David Rawson

Reputation: 21417

What about Single#zip?

fun main() {
    val singles = listOf(
        Single.just(1),
        Single.just(2),
        Single.just(3)
    )
    val list : Single<List<Int>> = Single.zip(singles) {
        it.toList() as List<Int>
    }
    
    list.test().assertResult(listOf(1,2,3))
}

Upvotes: 6

Laufwunder
Laufwunder

Reputation: 839

I solved it this way:

    val disposable = Observable.fromIterable(itemList).flatMapSingle { item ->
        getSingle(item)
            .map { singleResult ->
                // do something with single result
            }
    }.doOnComplete {
        // do stuff after processing all singles
    }.subscribe()

    addToCompositeDisposable(disposable)

It makes more sense working with the framework, than against it.

Upvotes: 1

Related Questions