Transforming Observables: RxJava

How to transform Observables from one type to another?

Say for example, a function is returning an observable of a list of strings, which are basically numbers. But, you finally need an observable of list of integers, and each of them need to be multiplied by 2, for some weird reason.

fun getStringList(): Observable<List<String>> {
return Observable.just(listOf("1", "2", "3", "4"))
}

and you need to write a function like this.

fun getIntList(): Observable<List<Int>> {
// ...
}

To achieve this, let’s write a mapper class template.

abstract class Mapper<T1, T2>() {
abstract fun map(value: T1): T2
}

And to actually carry out the transformation, let’s write another concrete class which extends the Mapper class.

class StringToIntMapper : Mapper<List<String>, List<Int>>() {
override fun map(value: List<String>): List<Int> {
val out = ArrayList<Int>()
value.forEach {
out.add(Integer.parseInt(it) * 2)
}
return
out
}
}

The above class, takes in the value of type List<String> and converts it to a List<Int>.

And finally, to complete the transformation, use the above class in your function.

fun getIntList(): Observable<List<Int>> {
return getStringList().map { StringToIntMapper().map(it) }
}

DONE!!! Easy….

Leave a Reply

Your email address will not be published. Required fields are marked *