Skip to content

Instantly share code, notes, and snippets.

@kohendrix
Created February 2, 2019 04:06
Show Gist options
  • Select an option

  • Save kohendrix/431be06b6518129aecd2cf693ea78961 to your computer and use it in GitHub Desktop.

Select an option

Save kohendrix/431be06b6518129aecd2cf693ea78961 to your computer and use it in GitHub Desktop.
Volley Coroutines Sample request() coroutines
suspend fun request(method: Int, url: String, headers: Map<String, String>, jsonRequest: JSONObject?): JSONObject {
return suspendCancellableCoroutine { continuation ->
val success = Response.Listener<JSONObject> { response -> continuation.resume(response) }
val error = Response.ErrorListener { error -> continuation.resumeWithException(error) }
val request = object : JsonObjectRequest(method, url, jsonRequest, success, error) {
override fun getHeaders(): Map<String, String> = headers
override fun parseNetworkError(volleyError: VolleyError): VolleyError {
return volleyError.networkResponse?.let {
Log.e("VolleyRequest", volleyError.networkResponse.headers.toString())
Log.e("VolleyRequest", String(volleyError.networkResponse.data))
VolleyError(String(volleyError.networkResponse.data))
} ?: volleyError
}
}
request.retryPolicy = DefaultRetryPolicy(5000, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
continuation.invokeOnCancellation { request.cancel() }
try {
Volley.newRequestQueue(applicationContext).addToRequestQueue(request) // must be singleton!!
} catch (e: Exception) {
continuation.resumeWithException(e)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment