Skip to content

Instantly share code, notes, and snippets.

@tralamazza
Created November 27, 2017 14:03
Show Gist options
  • Save tralamazza/866ea008058e926c64b4d13deb72660a to your computer and use it in GitHub Desktop.
Save tralamazza/866ea008058e926c64b4d13deb72660a to your computer and use it in GitHub Desktop.
// @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