Skip to content

Instantly share code, notes, and snippets.

View RoRoche's full-sized avatar

Romain Rochegude RoRoche

View GitHub Profile
@RoRoche
RoRoche / build_okhttp3.gradle
Created November 6, 2019 12:46
build.gradle for OkHttp3 dependency
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.2.2'
@RoRoche
RoRoche / RestRequest.kt
Last active November 19, 2019 18:05
Kotlin interface for RestRequest
import okhttp3.Response
interface RestRequest {
fun response(): Response
fun cancel()
abstract class Wrap protected constructor(
protected val origin: RestRequest
) : RestRequest by origin
import okhttp3.Call
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
class GetReposRequest(private val call: Call) : RestRequest {
constructor(client: OkHttpClient, baseUrl: String, user: String) : this(
client,
interface Repo {
fun id(): Long
fun name(): String
fun description(): String
fun url(): String
}
import org.json.JSONObject
class JsonRepo(private val jsonObject: JSONObject) : Repo {
override fun id(): Long = jsonObject.getLong("id")
override fun name(): String = jsonObject.getString("name")
override fun description(): String = jsonObject.getString("description")
import okhttp3.Response
import org.json.JSONArray
class JsonRepos(private val repos: List<Repo>) : List<Repo> by repos {
constructor(json: String) : this(JSONArray(json))
constructor(jsonArray: JSONArray) : this(
(0 until jsonArray.length())
.map(jsonArray::getJSONObject)
.map { JsonRepo(it) }
val repos: List<Repo> = JsonRepos(
GetReposRequest(
client = client,
baseUrl = "https://api.github.com/",
user = "RoRoche"
)
)
import android.util.Log
import okhttp3.Response
class LoggableRequest(
origin: RestRequest,
private val tag: String = origin.javaClass.simpleName
) : RestRequest.Wrap(origin) {
override fun response(): Response {
Log.d(tag, "response - started")
val response = super.response()
val repos: List<Repo> = JsonRepos(
WithBodyRestRequest(
SuccessfulRestRequest(
LoggableRequest(
GetReposRequest(
client = client,
baseUrl = "https://api.github.com/",
user = "RoRoche"
)
)
D/GetReposRequest: response - started
D/GetReposRequest: response - done with Response{protocol=http/1.1, code=200, message=OK, url=https://api.github.com/users/RoRoche/repos}