Search code examples
rx-javarx-java2

RxJava - Iterating a Single<Collection>


I have a method which returns a Single<Collection<SomeObj>>. What is the correct way to iterate through it so I can apply a filter and only return the SomeObj I'm looking for?


Solution

  • You could use flattenAsObservable. It converts a single of an iterable to an observable that emits each item:

    getItems()
        .flattenAsObservable { it }
        .filter { <some condition> }
        .first()
    

    Here the getItems returns Single<Collection<SomeObj>>.

    This code will return an observable. You might need to convert it back to a single. Be careful, if there are no elements, then it cannot be covered to single unless you specify a default value.