3

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?

Denis Belfort
  • 51
  • 1
  • 4

2 Answers2

3

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) }
AlexTa
  • 5,133
  • 3
  • 29
  • 46
0

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"))
Ernest Zamelczyk
  • 2,562
  • 2
  • 18
  • 32