Reputation: 11
I never use async in Kotlin. I'm not sure whether I understand is correctly.
I need that the method buttonChange(result) wait the thread is finish, to obtain the result.
fun sendConnection(view: View) {
var result = ""
if (!connected) {
async {
val runnable = Runnable()
{
result = me.connect("connection")
}
val threadSend = Thread(runnable)
threadSend.start()
}
buttonChange(result)
}
catch (e: Exception) {}
} else {
try {
async {
val runnable = Runnable()
{
result = me.connect("disconnection")
}
val threadSend = Thread(runnable)
threadSend.start()
}
buttonChange(result)
} catch (e: Exception) {
}
}
Upvotes: 0
Views: 334
Reputation: 39863
The pattern you should use is async/await
.
It'll return a Deferred
from async { }
which you can use to call await()
on. Since buttonChange
seems to need the UI
context, you might need to launch the coroutines as well.
launch(UI) {
try {
val result = async { me.connect("disconnection") }
buttonChange(result.await())
} catch (_: Exception) { }
}
You should not create a thread manually.
Upvotes: 2