SubwayTooter-Android-App/app/src/main/java/jp/juggler/subwaytooter/util/SimpleHttpClient.kt

71 lines
2.0 KiB
Kotlin
Raw Normal View History

2018-01-12 10:01:25 +01:00
package jp.juggler.subwaytooter.util
import android.content.Context
2018-09-30 17:00:28 +02:00
import jp.juggler.subwaytooter.App1
import jp.juggler.util.log.LogCategory
import okhttp3.*
import ru.gildor.coroutines.okhttp.await
2018-01-12 10:01:25 +01:00
// okhttpそのままだとモックしづらいので
// リクエストを投げてレスポンスを得る部分をインタフェースにまとめる
interface SimpleHttpClient {
var onCallCreated: (Call) -> Unit
// fun getResponse(
// request: Request,
// tmpOkhttpClient: OkHttpClient? = null
// ): Response
suspend fun getResponse(
request: Request,
tmpOkhttpClient: OkHttpClient? = null,
): Response
fun getWebSocket(
request: Request,
webSocketListener: WebSocketListener,
): WebSocket
2018-01-12 10:01:25 +01:00
}
class SimpleHttpClientImpl(
val context: Context,
private val okHttpClient: OkHttpClient,
) : SimpleHttpClient {
companion object {
val log = LogCategory("SimpleHttpClientImpl")
}
override var onCallCreated: (Call) -> Unit = {}
// override fun getResponse(
// request: Request,
// tmpOkhttpClient: OkHttpClient?
// ): Response {
// App1.getAppState(context).networkTracker.checkNetworkState()
// val call = (tmpOkhttpClient ?: this.okHttpClient).newCall(request)
// onCallCreated(call)
// return call.execute()
// }
override suspend fun getResponse(
request: Request,
tmpOkhttpClient: OkHttpClient?,
): Response {
App1.getAppState(context).networkTracker.checkNetworkState()
val call = (tmpOkhttpClient ?: this.okHttpClient).newCall(request)
onCallCreated(call)
return call.await()
}
override fun getWebSocket(
request: Request,
webSocketListener: WebSocketListener,
): WebSocket {
App1.getAppState(context).networkTracker.checkNetworkState()
return okHttpClient.newWebSocket(request, webSocketListener)
}
2018-01-12 10:01:25 +01:00
}