Created
November 27, 2017 14:03
-
-
Save tralamazza/866ea008058e926c64b4d13deb72660a to your computer and use it in GitHub Desktop.
This file contains 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
// @see https://www.avespeak.com/index.php?title=Choocher | |
object APIChoocher { | |
const val BASE_URL = "https://jsonplaceholder.typicode.com" | |
suspend fun posts(): JSONObject = request("api/posts") | |
suspend fun post(id: String): JSONObject = request("api/posts/$id") | |
suspend fun postCreate(title: String, body: String, userId: Int): JSONObject = | |
request("api/posts", Request.Method.POST, JSONObject(mapOf("title" to title, "body" to body, "userId" to userId))) | |
/** | |
* e.g. call it in your Application.onCreate() passing `applicationContext` | |
*/ | |
fun initialize(context: Context) { | |
mQueue = Volley.newRequestQueue(context) | |
mQueue.start() | |
} | |
private lateinit var mQueue: RequestQueue | |
private suspend fun request(path: String, method: Int = Request.Method.GET, body: JSONObject? = null): JSONObject = suspendCoroutine { cont -> | |
mQueue.add(JsonObjectRequest(method, "$BASE_URL/$path", body, | |
Response.Listener { response -> cont.resume(response) }, | |
Response.ErrorListener { error -> cont.resumeWithException(error) })) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment