Search code examples
androidkotlinretrofitretrofit2

How to take retrofit response body out of the function instead of just passing it to another function?


How do I assign the response body to a variable outside of the function, or return this response body somehow?

private fun getMyData() {
    val retrofitBuilder = Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl(BASE_URL)
        .build()
        .create(ApiInterface::class.java)

    val retrofitData = retrofitBuilder.getData()

    retrofitData.enqueue(object : Callback<WeatherData?> {
        override fun onResponse(call: Call<WeatherData?>, response: Response<WeatherData?>) {
            val responseBody = response.body()!!
            val x = responseBody.current_weather.temperature
            processData(responseBody)
        }

        override fun onFailure(call: Call<WeatherData?>, t: Throwable) {
            TODO("Not yet implemented")
        }
    })
}

I tried making a WeatherData class, but I couldn't make it work as it was always giving me some error and I'm very new to kotlin and OOP in general. So here I'm just passing the response body to the function processData.

I'm a complete beginner to android app development and Kotlin, but I know some Java. I'm trying to learn by doing instead of watching tutorials, but idk if that is the right way.


Solution

  • You can create a top-level lateinit variable but be careful with this because your app will crash if you try to access it without initializing it. After the api call, assign the response to that variable. This should do.