I am new to RxJava2 and its methods. I need to change the data type which is emitted from an Observable.
Say, I have a data class like below.
data class SomeClass (val type: String)
An API returns ArrayList<SomeClass>
, this works fine on the current implementation using RxJava2 and RxAndroid.
apiService.getPrice(code)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(singleObserver)
I have to change/transform the data from ArrayList<SomeClass> to HashMap<someClassObject.type, ArrayList<SomeClass>>
. I am trying operators to make this happen, but no operator will allow changing the datatype being observed.
Transform based on:
Consumer<ArrayList<SomeClass>> { response ->
val mapped = HashMap<String, ArrayList<SomeClass>>()
response.forEach { someClassObj ->
val type = someClassObj.type!!
if (mapped.containsKey(type)) {
mapped[district]?.add(someClassObj)
} else {
val list = ArrayList<SomeClass>()
list.add(someClassObj)
mapped[type] = list
}
}
}
I am thinking to use two different observables, in which Observable data #2 is based on the response of Observable data #1 (ArrayList<SomeClass>
). But, I am not sure if this works. Any better or efficient way to achieve this?
Try map
:
apiService.getPrice(code)
.map { response ->
val mapped = HashMap<String, ArrayList<SomeClass>>()
response.forEach { someClassObj ->
val type = someClassObj.type!!
if (mapped.containsKey(type)) {
mapped[district]?.add(someClassObj)
} else {
val list = ArrayList<SomeClass>()
list.add(someClassObj)
mapped[type] = list
}
}
mapped
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(singleObserver);