Search code examples
androidrx-javarx-java2rx-android

Combine two variables in one request using Rx


I want to combine company and workFor variables into one stream, but I don't know how. I tried to use switchMap, zip, merge and concatMapIterable but nothing worked. Or I did something wrong..

My data model:

 data class UserCompany(
    @field:Json(name = "user") val user: User,
    @field:Json(name = "company") val company: Company,
    @field:Json(name = "workFor") val workFor: List<Company>
)

And my current code:

    authApi.getCompany(getJwt()) //here I get data that looks like the above model
           .subscribeOn(Schedulers.io())
           .flatMapIterable { 
                return@flatMapIterable it.data.workFor.toMutableList().add(it.data.company) //error Type mismatch
           },

//should returns stream of company and workFor

How to combine two variables from one request using Rx?

Edit, better example. Let's say we have:

data class Pet(val name: String)

data class PetResult(
    val myPet: Pet, //dog
    val otherPet: List<Pet> //cat, bird, cow
)

And i wannt to get something like this:

authApi.getPet() // response looks like PetResult (model above)
    .subscribeOn(Schedulers.io())
    .subscribe(
        { petList.setSuccess(it) }, // should returns dag, cat, bird, cow
        { petList.setError(it.message) }
    )

So, how to merge myPet with otherPet that i get from one API request?


Solution

  • You can achieve the above example like below:

        apiClient.getPet.flatMap {
            var getListResponse=it;  
            //From getListResponse you will get Result obj which contain pet and other pet list
            var pet=it.getPet()
            var petList=it.getPetList()
            petList.add(pet)
            getListResponse.setPetList=petList
    
        }