简体   繁体   中英

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

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?

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM