Search code examples
androidkotlinrx-java2

Map models to entities in nested Maybe


I have a function which takes a model and maps it to an entity. This is entity is passed into another function which returns a maybe.

I do not want to run the mapping process on the mainThread, so I created a nested maybe.

//Returns the id of the inserted exam
fun insertExamIntoDatabase(examModel: ExamModel): Maybe<Long> = Maybe.create { emitter ->
//Do heavy work like mapping objects
Thread.sleep(5000)
val entity = ExamMapper.toEntity(examModel)
examLocalSource.insertExam(entity).subscribe({
    emitter.onSuccess(it)
}, {
    emitter.onError(it)
})

This functions works but it does not look like clean code. Also I am concerned about things like memory leaks if you work with larger data.

Is there any way, how I can improve this method?

Thanks for helping.


Solution

  • Perfect use case for flatMap:

    fun insertExamIntoDatabase(examModel: ExamModel): Maybe<Long> = 
       Maybe.create { emitter ->
          //Do heavy work like mapping objects
          Thread.sleep(5000)
          emitter.onSuccess(ExamMapper.toEntity(examModel))
       }.flatMap { entity -> examLocalSource.insertExam(entity) }