Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin transformation of objects to another objects

http://cm08323.tmweb.ru/android/determinace/json/images.json I have some json to the server.

My database class:

@Entity
data class Image(val url: String = "", val urlAnswer: String = "", val race: String = "") : DisplayableItem, Persistable

Interface for api:

interface ImagesAdi {
    @GET("android/determinace/json/images.json")
    fun getImages(): Single<List<ImagesResponse>>
}
...
class ImagesResponse(
        val images: List<ImageSingle>)

class ImageSingle(val url: String,
            val url_answer: String,
            val race: String)

My mapper for transformation ImagesResponse to Image:

@Singleton
class ChooseRaceMapper @Inject constructor() : (ImageSingle) -> Image {
    override fun invoke(response: ImageSingle): Image = Image(response.url, response.url_answer, response.race)
}

How should look like transformer from List< ImageSingle > to List< Image >?

I have trasformer for single objects, he looks like that:

fun chooseRace(): Single<Image> = imagesAdi.getSingleImage()
        .map { chooseRaceMapper.invoke(it) }
        .doOnSuccess {
            database.addDetectedResult(it)
                    .subscribeIgnoreResult()

            requestImages()
        }

Can you help me to write transformer for type "List"? I trying make it, but it did not work out. Thanks. Sorry for my English.

Or transformation from List to List should be better in class Mapper? (In method invoke)

like image 887
Tipok Avatar asked Oct 18 '22 12:10

Tipok


2 Answers

Considering your images.json, your getImages() should not return a Single of a List.

@GET("android/determinace/json/images.json")
fun getImages(): Single<ImagesResponse>

Then you could use the Kotlin List.map() mapper to map the list.

imagesAdi.getImages()
    .map { list -> list.map { chooseRaceMapper.invoke(it) } }
    .doOnSuccess { }
like image 102
tynn Avatar answered Oct 21 '22 05:10

tynn


The interface declaration is wrong:

interface ImagesAdi {
    @GET("android/determinace/json/images.json")
    fun getImages(): Single<List<ImagesResponse>>
}

It should be (according to your json):

interface ImagesAdi {
    @GET("android/determinace/json/images.json")
    fun getImages(): Single<ImagesResponse>
}

And for the mapping part, something like this will do:

imagesAdi.getImages().map { it.images }
    .map { /* your mapper here */ }
    ...
like image 28
johnny_crq Avatar answered Oct 21 '22 05:10

johnny_crq