Created
February 2, 2019 04:06
-
-
Save kohendrix/431be06b6518129aecd2cf693ea78961 to your computer and use it in GitHub Desktop.
Volley Coroutines Sample request() coroutines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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