RxJava Kotlin how to get separated objects from single observable<String>

Viewed 3152

RxJava Kotlin flatmap don't return separated objects from splitted string. instead it returns List

val source: Observable<String> = Observable.just("521934/2342/FOXTROT")
.flatMap{Observable.fromArray(it.split("/"))}
.subscribe{Log.d(TAG, "$it")}

It returns list:

[521934, 2342, FOXTROT]

But book (Thomas Nield : Learning RxJava / 2017 / Page 114) says it has to return separated strings

521934
2342
FOXTROT   

example from book

http://reactivex.io/documentation/operators/flatmap.html says that it returns Single object. In my case I got Single List object. So, documentation says true. But I want to get result as in book example!

How I can split the list and get separated objects?

2 Answers

Make use of flatMapIterable, so you can get a stream of the items from the list:

Observable.just("521934/2342/FOXTROT")
            .flatMap { input -> Observable.fromArray(input.split("/")) }
            .flatMapIterable { items -> items }
            .subscribe { item -> Log.d(TAG, item) }

Just use fromIterable:

Observable.just("521934/2342/FOXTROT")
                .flatMap { Observable.fromIterable(it.split("/")) }
                .subscribe{
                    Log.d(TAG, "$it")
                }

In case of array you would have to use a spread operator additionaly since fromArray takes a vararg argument list:

Observable.fromArray(*arrayOf("521934","2342","FOXTROT"))
Related