Home > Back-end >  How to get response headers in my ViewModel using retrofit2 and reactivex?
How to get response headers in my ViewModel using retrofit2 and reactivex?

Time:09-02

In my ViewModel I invoke a REST service via a Repository and a NetworkProvider which creates the service i.e. the interface which uses retrofit2 and reactivex to perform a GET, as described in the code below. How can I get in my ViewModel a specific Header from the service Response?

class MyViewModel(val repository: Repository) : ViewModel {
    private val disposable = CompositeDisposable()
    val responseLiveData = MutableLiveData<SingleEvent<ServiceResponse>>()
    val errorLiveData = MutableLiveData<SingleEvent<Boolean>>()

    private fun loadDataPaged(owner: String, page: Int, perPage: Int) {
        disposable.add(
            repository.loadDataSingle(owner, page, perPage)
                .subscribeOn(Schedulers.io())
                .subscribe({ response ->
                    // ... how to get a specific response header here?
                    responseLiveData.postValue(SingleEvent(response))                    
                }, { exc ->
                    errorLiveData.postValue(SingleEvent(true))
                })
        )
    }
}


class Repository {
    private val networkProvider = NetworkProvider()

    fun loadDataSingle(owner: String, page: Int, perPage: Int): Single<ServiceResponse> {
        return networkProvider.loadDataSingle(owner, page, perPage)
    }

}


class NetworkProvider {
    private lateinit var authService: ApiService

    init {
      createService()
    }

    private fun createService() {
      // code to create the service ApiService...
    }

    fun loadDataSingle(owner: String, page: Int, perPage: Int): Single<ServiceResponse> {
        return authService.loadData(owner, page, perPage)
    }
}


interface ApiService {
    @GET("/repos/{owner}/data")
    fun loadData(
        @Path("owner") owner: String,
        @Query("page") page: Int,
        @Query("per_page") perPage: Int
    ): Single<ServiceResponse>
}

CodePudding user response:

You need to wrap up your response return type with Response.

 @GET("/repos/{owner}/data")
    fun loadData(
        @Path("owner") owner: String,
        @Query("page") page: Int,
        @Query("per_page") perPage: Int
    ): Single<Response<ServiceResponse>>

After that, you can get headers via headers() function.

  • Related