Search code examples
androidretrofitandroid-architecture-componentsandroid-livedataretrofit2.6

Need help Kotlin Coroutines, Architecture Component and Retrofit


I'm trying to wrap my head around the mentioned components and I can't get it right. I want to do something very simple: Fetch data from the network and present it to the user. Currently am not yet caching it as am still learning new Coroutine features in Architecture components. Every time app loads I get an empty model posted, which seems weird.

My API is get hit fine and response is 200 which is OK.

Below is what I have attempted:

POJO

data class Profile(@SerializedName("fullname") val fullName : String.....)

Repository

class UserRepo(val context: Context, val api: Api) {

    suspend fun getProfile(): Profile
    {
        val accessToken = ....
        return api.getUserProfile(accessToken)

    }
}

API

interface GatewayApi {
    @GET("users/profile")
    suspend fun getUserProfile(@Query("access-token") accessToken: String?): Profile
}

ViewModel

class UserViewModel(application: Application) : AndroidViewModel(application) {
    private val usersRepo = UserRepo(application.applicationContext, Apifactory.Api)
    val userProfileData = liveData{
        emit(usersRepo.getProfile())
    }

    fun getProfile() = viewModelScope.launch {
        usersRepo.getProfile()
    }
}

Finally my fragment's relevant code

val viewModel = ViewModelProviders.of(activity!!).get(UserViewModel::class.java)
viewModel.userProfileData.observe(this, Observer<UserProfile> {
     //it is having nulls
 })

//trigger change
viewModel.getProfile()

Solution

  • So I added HTTP requests and responses (thanks to @CommonsWare for pointing that out) and it happened I had used a different model than I was supposed to use. The correct model that mapped the JSON response was ProfileResponse and as you can see in my posted code, I used Profile instead. So all fields were empty as Gson could not correctly serialize JSON into Profile object.

    All the credit goes to @CommonsWare for pointing that out in comment.