Can I do a synchronous request with volley?

后端 未结 8 1679
执念已碎
执念已碎 2020-11-22 11:02

Imagine I\'m in a Service that already has a background thread. Can I do a request using volley in that same thread, so that callbacks happen synchronously?

There ar

8条回答
  •  执念已碎
    2020-11-22 11:47

    You achieve this with kotlin Coroutines

    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7"
    
    private suspend fun request(context: Context, link : String) : String{
       return suspendCancellableCoroutine { continuation ->
          val queue = Volley.newRequestQueue(context)
          val stringRequest = StringRequest(Request.Method.GET, link,
             { response ->
                continuation.resumeWith(Result.success(response))
             },
              {
                continuation.cancel(Exception("Volley Error"))
             })
    
          queue.add(stringRequest)
       }
    }
    

    And call with

    CoroutineScope(Dispatchers.IO).launch {
        val response = request(CONTEXT, "https://www.google.com")
        withContext(Dispatchers.Main) {
           Toast.makeText(CONTEXT, response,Toast.LENGTH_SHORT).show()
       }
    }
    

提交回复
热议问题