0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JetpackCompose でAPI呼んでみた

0
Last updated at Posted at 2026-09-12

JetpackCompose の実装

JetpackCompose でAPIを呼ぶ処理を実装していきます。
ここではQiitaのAPIを使用します。

使用するライブラリ

使用技術は以下の通りです。
※この組み合わせの場合アノテーションが大量に出てきます。

  • Compose
     画面を実装するやつ
  • Hilt
     依存性注入
  • Retrofit
     APIを呼ぶ仕組み
  • kotlinx.serialization
     APIのより取得したJSONを自動でクラスにマッピングする

APIを呼ぶまでの処理の流れ

  1. Qiita API
    ↓
  2. QiitaAPI
    ↓
  3. Repository
    ↓
  4. UseCase
    ↓
  5. ViewModel
    ↓
  6. Compose

1. Qiita API

とりあえず以下のAPIをコールしてみます。
https://qiita.com/api/v2/items?page=1&per_page=20

2. QiitaAPI

interface QiitaApi {
    @GET("api/v2/items")
    suspend fun getItems(
        @Query("page") page: Int = 1,
        @Query("per_page") perPage: Int = 20,
    ): List<QiitaItemResponse>
}

3. Repository

  • Interface
interface QiitaRepository {
    suspend fun getItems(): Result<List<QiitaItemResponse>>
}
  • Implementation
class QiitaRepositoryImpl @Inject constructor(
    private val qiitaApi: QiitaApi
) : QiitaRepository {
    override suspend fun getItems(): Result<List<QiitaItemResponse>> {
        return try {
            val items = qiitaApi.getItems()
            Result.Success(items)
        } catch (e: Exception) {
            Result.Error(e)
        }
    }

4. UseCase

class GetQiitaItemsUseCase @Inject constructor(
    private val repository: QiitaRepository
) {
    suspend operator  fun invoke(): Result<List<QiitaItemResponse>> {
        return repository.getItems()
    }
}

5. ViewModel

@HiltViewModel
class QiitaViewModel @Inject constructor(
    private val getQiitaItemsUseCase: GetQiitaItemsUseCase,
) : ViewModel() {
    private  val _items = MutableStateFlow<List<QiitaItemResponse>>(emptyList())

    val items = _items.asStateFlow()

    init {
        getItems()
    }

    private fun getItems() {
        viewModelScope.launch {
            when (val result = getQiitaItemsUseCase()) {
                is Result.Success -> {
                    _items.value = result.data
                }

                is Result.Error -> {
                    println(result.exception)
                }

                Result.Loading -> {
                }
            }
        }
    }
}

6. Compose

@Composable
fun QiitaListScreen(
    viewModel: QiitaViewModel = hiltViewModel()
) {
    val items by viewModel.items.collectAsStateWithLifecycle()

    Column {
        Spacer(Modifier.height(20.dp))
        SearchForm()
        LazyColumn {
            items(items) { item ->
                Text(
                    text = item.title
                )
            }
        }
    }
}

Module

  • RepositoryModule
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
    @Binds
    abstract fun bindQiitaRepository(
        impl: QiitaRepositoryImpl
    ): QiitaRepository
}
  • NetworkModule
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
    @Provides
    @Singleton
    fun provideJson(): Json {
        return Json {
            ignoreUnknownKeys = true
        }
    }

    @Provides
    @Singleton
    fun provideRetrofit(
        json: Json
    ): Retrofit {
        return Retrofit.Builder().baseUrl("https://qiita.com/").addConverterFactory(json.asConverterFactory("application/json".toMediaType())).build()
    }

    @Provides
    @Singleton
    fun provideQiitaApi(
        retrofit: Retrofit
    ): QiitaApi {
        return retrofit.create(QiitaApi::class.java)
    }
}

Model

  • QiitaItemResponse
@Serializable
data class QiitaItemResponse(
    val id: String,
    val title: String,
    val url: String,
    @SerialName("likes_count")
    val likesCount: Int
)
  • Result
sealed class Result<out T> {
    data object Loading : Result<Nothing>()

    data class Success<T>(
        val data: T
    ) : Result<T>()

    data class Error(
        val exception: Throwable
    ) : Result<Nothing>()
}

参考

大量にアノテーションが出てきます。
以下のように整理しましたので、参考まで。

アノテーション一覧

分類 アノテーション 役割
Compose @Composable UI関数
Hilt @HiltAndroidApp DIの起点
Hilt @AndroidEntryPoint Activity等をDI対象にする
Hilt @HiltViewModel ViewModelをHilt管理にする
Hilt @Inject constructor注入
Hilt @Module DI設定クラス
Hilt @InstallIn Moduleの適用範囲
Hilt @Binds interfaceと実装を紐付け
Hilt @Provides オブジェクトの生成方法を定義
Hilt @Singleton 1インスタンス共有
Retrofit @GET GETリクエスト
Retrofit @Query クエリパラメータ
Serialization @Serializable JSON変換対象
Serialization @SerialName JSON名とKotlin名の対応付け
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?