Search code examples
androidkotlinretrofit2clean-architecturerx-java3

A 'return' expression required in a function with a block body ('{...}'


I want to call api using rxjava3 inside getCampaigns function in CampaignRepositoryImpl.kt class but I am getting following error error A 'return' expression required in a function with a block body ('{...}')

below CampaignRepositoryImpl.kt class

import de.westwing.campaignbrowser.domain.Campaign
import de.westwing.campaignbrowser.domain.CampaignRepository
import io.reactivex.rxjava3.core.Single

class CampaignRepositoryImpl(private val apiInterface: ApiInterface) : CampaignRepository {

    override fun getCampaigns(): Single<List<Campaign>> {

       apiInterface.getCampaigns()

    }

}

below my interface class I am getting API call

interface ApiInterface {

    @GET("cms/test/campaigns.json")
    fun getCampaigns(): Single<CampaignsResponse>

}

below CampaignRepository

interface CampaignRepository {

fun getCampaigns(): Single<List<Campaign>>

}

below my CompaignResponse.kt

data class CampaignsResponse(val metadata: CampaignsMetadata)

below CampaingsMetadata

data class CampaignsMetadata(val data: List<CampaignDto>)

below

data class Campaign(val name: String, val description: String)

below CampaignDto

class CampaignDto(val name: String, val description: String, val image: ImageDto)

I want to know where I am making mistake what I have to do in order to avoid error


Solution

  • From your api interface, we can see that the type of getCampaigns() is Single<CampaignsResponse>. In your repository implementation, on the other hand, the type of getCampaigns() is Single<List<Campaign>>.

    Since both are Single<Foo>, you'll need to map from one to the other.

    Given your class implementations, this should work:

    override fun getCampaigns(): Single<List<Campaign>> {
       return apiInterface.getCampaigns().map { response ->
           response.metadata.data.map {
               Campaign(it.name, it.description)
           }
       }
    }
    

    This map call is taking a CampaignResponse and turning it into a List<Campaign>.