LoginSignup
0
0

KotlinでFuelを使った時にデータが格納できなかった時の備忘録

Last updated at Posted at 2023-05-23

Android開発の練習として、qiitaの記事を見るようなクライアントアプリを作る時に、Fuelを使ってデータの取得を試みたが、値が上手く格納できなかった

使っていたライブラリ(Fuel関係のみ)

build.gradle(app)
dependencies {
    implementation "com.github.kittinunf.fuel:fuel:2.3.1"
    implementation "com.github.kittinunf.fuel:fuel-android:2.3.1"
    implementation "com.github.kittinunf.fuel:fuel-json:2.3.1"
}

試しに普通にAPIを呼ぶ関数を作成し、onStart()でAPIコールしてみる
(testList変数がプロパティとして存在する想定)

Fuel.get(url).responseJson { request, response, result ->
    when (result) {
        is Result.Failure -> {
             
        }
        is Result.Success -> {
            var list = JSONArray(result.get().array())
            for (i in 0 until list.length()) {
                testList.add()
            }
        }
    }
}

testListのsizeが0のまま処理が進んでしまう

非同期処理のため、APIのレスポンスを待たずに次の処理に移ってしまうため
fuel-coroutinesを使ってAPIコールするように変更した

build.gradle(app)
dependencies {
    implementation "com.github.kittinunf.fuel:fuel:2.3.1"
    implementation "com.github.kittinunf.fuel:fuel-android:2.3.1"
    implementation "com.github.kittinunf.fuel:fuel-json:2.3.1"
    implementation "com.github.kittinunf.fuel:fuel-coroutines:2.3.1" //追加
}
runBlocking {
    val (_, _, result) = url.httpGet().awaitStringResponseResult()
    result.fold(
        { data ->
            var list = JSONArray(data)
            for (i in 0 until list.length()) {
                testList.add()
            }
        },
        { error -> Log.e(TAG, "An error of type ${error.exception} happened: ${error.message}") }
    )
}

これでtestListに値が入ってから処理が進む

違和感が凄いもののこの使い方はあってるのだろうか・・・・・

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0