My server api looks like this:
data class ArticleDTO(val id: Int, val title: String, val typeId: Int)
data class Type(val id: Int, val name: String)
interface API {
fun getArticles(): Single<List<ArticleDTO>>
fun getTypes(): Single<List<Type>>
}
And I have one model which I use in UI:
data class Article(val title: String, val typeName: String)
I created map method:
fun ArticleDTO.toArticle(type: Type) = Article(this.title, typeName = type.name)
And in the repository class I did this:
fun getArticles() =
Observables.combineLatest(api.getArticles().toObservable(), api.getTypes().toObservable())
.flatMap {
Observable.just(it.first.map { articleDTO ->
articleDTO
.toArticle(it.second.find { type -> type.id == articleDTO.typeId }!!)
})
}
Is there a way to do it better?
And what if my api will looks like this:
interface API {
fun getArticles(): Single<List<ArticleDTO>>
fun getTypes(typeId: Int): Single<Type>
}
You can get rid of flatMap
and Observable.just
fun getArticles() = Observables.combineLatest(api.getArticles().toObservable(), api.getTypes().toObservable())
.map { (dtos, types) ->
dtos.map { articleDTO ->
articleDTO
.toArticle(types.find { type -> type.id == articleDTO.typeId }!!)
}
}