https://kotlinlang.org logo
#android
Title
# android
m

Mehdi

01/16/2019, 9:47 AM
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

540grunkspin

01/16/2019, 10:21 AM
Why do you need the
result
variable?
m

Mehdi

01/16/2019, 10:48 AM
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

540grunkspin

01/16/2019, 1:13 PM
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

dave08

01/17/2019, 3:26 AM
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

540grunkspin

01/17/2019, 8:44 AM
@dave08Cool have completely missed
withContext
m

Mehdi

01/17/2019, 4:26 PM
thank you very very much @540grunkspin @dave08, I got exactly what I was looking for
u

540grunkspin

01/17/2019, 5:37 PM
No problemo!