くうと徒然なるままに

モバイルアプリを作りながらバックエンドも作っています。

Android の Fuel + Moshi + Kotlin Coroutine でいい感じにする拡張関数を書いた

Fuel には、 mochi、 Kotlin Coroutine といい感じに連携してくれる機能があります。 けど、 Moshiと Kotlin Coroutine を組み合わせていい感じに呼び出せる関数は存在してないです。(まぁ、標準で存在してても依存関係考えたら載せるべきでないのはそう)(存在してたら教えて!書き換えるから!)

とはいえ、冗長な感じで書いてくのも大変なのでいい感じに移植してきます。

コード

import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import com.github.kittinunf.fuel.core.response
import com.github.kittinunf.fuel.moshi.moshiDeserializerOf
import com.github.kittinunf.result.Result
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.GlobalScope
import kotlinx.coroutines.experimental.async

// Response が欲しいとき
inline fun <reified T : Any> Request.awaitResponseObject(): Deferred<Triple<Request, Response, Result<T, FuelError>>> {
  val request = this
  return GlobalScope.async {
    return@async request.response(moshiDeserializerOf<T>())
  }
}

// Result だけが欲しいとき
inline fun <reified T : Any> Request.awaitResultObject(): Deferred<Result<T,FuelError>> {
  val request = this
  return GlobalScope.async {
    return@async request.response(moshiDeserializerOf<T>()).third
  }
}

Request への拡張関数として書きました。
Moshi を使ってシリアライズするやつを Async で非同期に取得するようにしてるだけですね。