line 12
# android
m
I am getting the response when I try to access result, from outside. But since I am new to OOP and Kotlin and Android, I would really appreciate it if someone could criticize what I did, because I am not sure I chose the right implementation
u
Why do you need the
result
variable?
m
I can't get the response otherwise in Main Activity. Do you know a way I can avoid the result variable ? If yes, I would love to delete it
This is what I do in MainActivity : var inst = ForecastService("...") var s: Result<ForecastResponse> = runBlocking { inst.getResponse(37.8267, -122.4233) }
then, the only way I found to actually get the forecastResponse is to call inst.result.[GSON object] after these lines. But I doubt this is the way it should be done
u
Aaah! now i get it! You should be able to do:
Copy code
fun getResponse(lat: Double, long: Double): Deferred<Result<ForecastResponse>>{
    return async (<http://Dispatchers.IO|Dispatchers.IO>) {
        requestForecast(lat, long)
    }
}
and then
Copy code
launch (Dispatchers.Main) { 
    val response = inst.getResponse(37.8267, -122.4233).await()
}
But like many others said, If you want to use the value diesctly in the activity probably something like LiveData is a better option. The solution I provided above will just provide you with a one off value where as LiveData and ViewModel will update you on the value over time and keep it during configuration changes
👆🏼 2
d
It should be
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { }
if you await at the same time as calling. It comes out to the same and is more efficient. @540grunkspin
u
@dave08Cool have completely missed
withContext
m
thank you very very much @540grunkspin @dave08, I got exactly what I was looking for
u
No problemo!