Home > Blockchain >  Get string from cotoutine
Get string from cotoutine

Time:02-14

I'm confronted to a very simple issue, I'm trying to get a sid from a volley request, i've been able to implement a coroutine but i can't extract my data from the GlobalScope.launch() function, maybe it's not the great way to execute it I don't know, heres is my code I hope someone can help thanks.

GlobalScope.launch() {
    data = getData()
    println(data)
}

And here's my coroutines and my getData function

suspend fun getData() = suspendCoroutine<String> { cont ->
    val queue = Volley.newRequestQueue(this)
    val url = "http://www.google.com/"

    val stringRequest = StringRequest(Request.Method.GET, url,
        { response ->
            cont.resume("Response is: ${response.substring(0, 500)}")
        },
        { cont.resume("Something went wrong!") })

    queue.add(stringRequest)
} 
interface VolleyStringResponse {
    fun onSuccess(response: String?)
}

CodePudding user response:

Simple answer is: you can't.

This is all about waiting for the result. There are several ways to wait for something, the most common are: thread blocking, suspending (coroutines), callbacks and futures/premises. You already converted waiting through callbacks to suspending - which is good, because suspending is usually easier to handle than callbacks.

But if you think about something like this:

fun onClick() {
    val data = getData()
    doSomething(data)
}

Then this is impossible, at least not without blocking the thread which we should avoid. This is because non-suspending function can't wait in any other way than by blocking the thread.

Usually, we enclose a whole operation in a coroutine and inside it we execute operations sequentially, for example:

fun onClick() = lifecycleScope.launch {
    val data = getData()
    doSomething(data)
}

So instead of extracting the data to outside of the launch(), we move the subsequent step also into launch().

Also, we should avoid using GlobalScope. On Android you could/should usually use lifecycleScope or viewModelScope instead.

  • Related