0

In my project, I use RxJava/RxKotlin bindings to communicate with REST API. The API sometimes returns a list of elements, that need to be altered/mapped, before I can use them.

Currently, mapping of these elements is done by nested .map() and .apply() functions, like this:

fun getSampleObjects(): Single<List<SampleObject>> =
    sampleService.getSampleObjects()
        .map { list ->
            list.map { sampleObject ->
                sampleObject.apply {
                    sampleProperty = otherSampleService.getSampleProperty()
                }
            }
        }

where sampleService.getSampleObjects() returns and RxKotlin Single<List<SampleObject>>

I'm looking for an easier-to-read and more efficient way to archive the same result, possibly without the need to alter data models.

ikurek
  • 604
  • 11
  • 27

1 Answers1

1

Something like this could work quite nicely, and maintain immutability (if SampleObject is a data class):

data class SampleObject(val someProperty : Any, val otherProperty : Any)


fun getSampleObjects(): Single<List<SampleObject>> =
        sampleService.getSampleObjects()
                .toObservable()
                .flatMapIterable { it }
                .flatMapSingle { sampleObject -> 
                       otherSampleService.getSampleProperty()
                            .map { sampleObject.copy(someProperty = it) } 
                }.toList()
Mark
  • 9,604
  • 5
  • 36
  • 64
  • It looks better then nested `.map()`s, but it's not really much simpler. I'm looking for some kind of extension function or one-liner :-/ – ikurek Sep 10 '19 at 20:28
  • Well there are few things to consider: one it's now immutable, two it's pure RxJava, three you are restricted by your API flow requiring multiple steps and four this could be an extension function. However that would not make more readable just abstracted in a separate method, which you could argue makes it less readable. If you want less complicated consider redesigning the API calls that make this multi stepped. – Mark Sep 10 '19 at 21:24