I am making a really simple app in which I make points in a map with different icons, a weather map. The problem is that the function that I use lasts a while to extract the information in another thread. So the program keeps running and the value does not update when I use it.
This is the code of the API of the weather.
private val appid = "??"
private var icon: String = ""
fun tiempo_ciudad(id: String, context: Context, callback: (String) -> Unit) {
val tempUrl = "https://api.openweathermap.org/data/2.5/weather?id=" id "&appid=" appid
val stringRequest = StringRequest(
Request.Method.POST,
tempUrl,
{ response ->
val json = JSONObject(response)
val weather = json.getJSONArray("weather").getJSONObject(0)
icon = "_" weather.getString("icon")
callback(icon)
},
{ error ->
// maneja el error
}
)
val requestQueue = Volley.newRequestQueue(context)
requestQueue.add(stringRequest)
}
fun getIcon(id: String, context: Context, callback: (String) -> Unit) {
tiempo_ciudad(id, context) {
icon -> callback(icon)
}
}
And this is the code that I use to generate the point, is there some way to wait until getIcon works?
@Composable
fun generapunto(context: Context, id: String, x: Int, y:Int) {
var icon = ""
getIcon(id, context) { retrievedIcon ->
icon = retrievedIcon
}
val resourceId = context.resources.getIdentifier(icon, "mipmap", context.packageName)
Box( modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.padding(top = y.dp, start = x.dp)) {
Image(
painter = painterResource(resourceId),
contentDescription = null,
modifier = Modifier
.size(50.dp)
.clip(CircleShape)
.background(Color(red = 222f / 255f, green = 225f / 255f, blue = 250f / 255f))
)
}
}
CodePudding user response:
Example:
@Composable
fun generapunto(context: Context, id: String, x: Int, y:Int) {
var icon by remember { mutableStateOf("") }
LaunchedEffect(Unit) {
getIcon(id, context) { retrievedIcon ->
icon = retrievedIcon
}
}
if(icon.isNotBlank()) {
val resourceId = context.resources.getIdentifier(icon, "mipmap", context.packageName)
Box( modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.padding(top = y.dp, start = x.dp)) {
Image(
painter = painterResource(resourceId),
contentDescription = null,
modifier = Modifier
.size(50.dp)
.clip(CircleShape)
.background(Color(red = 222f / 255f, green = 225f / 255f, blue = 250f / 255f))
)
}
}
}