LoginSignup
6
7

More than 3 years have passed since last update.

【Kotlin】API通信をするための事前準備

Posted at

いつも忘れるのでメモ。

ライブラリへの依存を定義

  • okhttp3
  • retrofit2
  • moshi
  • Koin
build.gradle
dependencies {
    // API通信関連
    def okhttp_version = '3.11.0'
    implementation "com.squareup.okhttp3:okhttp:$okhttp_version"
    implementation "com.squareup.okhttp3:logging-interceptor:$okhttp_version"

    def retrofit_version = '2.6.0'
    implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
    implementation "com.squareup.retrofit2:converter-moshi:$retrofit_version"

    def moshi_version = '1.8.0'
    implementation "com.squareup.moshi:moshi:$moshi_version"
    implementation "com.squareup.moshi:moshi-kotlin:$moshi_version"

    // DI
    implementation 'org.koin:koin-androidx-viewmodel:1.0.2'
}

ApiClientオブジェクトを作成

ApiClient.kt

object ApiClient {
    private const val BASE_URL = "https://qiita.com/"

    val moshi: Moshi = Moshi.Builder()
        .build()

    var retrofit: Retrofit

    init {
        val okHttpClient = OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            })
            .build()

        retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .baseUrl(BASE_URL)
            .build()
    }
}
  • シングルトンで作る
  • okhttp、retrofit、moshiを立ち上げる
  • BASE_URLはこの中で定義しておくとわかりやすい気がする

KoinModuleオブジェクトを作成

KoinModule.kt
object KoinModule {
    val modules = listOf(
        dataModule(),
        domainModule(),
        uiModule()
    )

    private fun dataModule() = module {
        single { ApiClient.retrofit }
    }

    private fun domainModule() = module {
        // あとで追加する
    }

    private fun uiModule() = module {
        // あとで追加する
    }
}
  • シングルトンで作る
  • DIのメリットはテストがしやすくなる&柔軟なコードになること
  • このファイルでは依存関係の解決を行う
  • 階層によって分けておくと管理がしやすい

Applicationクラスを作成

Application.kt
class Application : android.app.Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin(this, KoinModule.modules)
    }
}
AndroidManifest.xml

<application
    android:name=".Application"
    ...>
</application>

→ここまできたらあとはServiceを作成してAPIを呼び出せばOK

6
7
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
6
7