LoginSignup
0
0

恥ずかしがり屋の ViewModel

Last updated at Posted at 2023-12-01

はじめに

Android Advent Calendar 2023 2日目の記事です。

恥ずかしがり屋の ViewModel ということで property を公開しすぎないようにしたいです。

UI state

イメージとしては下図の UI state の部分のみを ViewModel は公開します。

Figure 4. Diagram of how UDF works in app architecture.

1日目に続き Android Developers でガイドで示されているサンプルからコードを抜粋して紹介します。

Good

StateFlow を公開するのがシンプルでわかりやすいです。

    private val _state = MutableStateFlow(HomeViewState())    

    val state: StateFlow<HomeViewState>
            get() = _state

HomeViewState の中身は次のようになっています。
State が Immutable なのが良いです。

data class HomeViewState(
    val featuredPodcasts: PersistentList<PodcastWithExtraInfo> = persistentListOf(),
    val refreshing: Boolean = false,
    val selectedHomeCategory: HomeCategory = HomeCategory.Discover,
    val homeCategories: List<HomeCategory> = emptyList(),
    val errorMessage: String? = null
)

Bad

もし State を用意していなくて、単純に更新中の制御をしたいとして、次のような property を追加したとします。

    var refreshing by mutableStateOf(false)

View からも状態を更新できるので一見便利かもしれないですが、コードは難解になっていきます。また ViewModel の property を操作できてしまうが故に、1日目で紹介した ViewModel に依存した Composable を生みやすくなっています。

@Composable
fun Home() {
    HomeContent(
        viewModel = viewModel
    )
}

@Composable
fun HomeContent(
    viewModel: HomeViewModel
) {
    if (viewModel.refreshing) {
        CancelableIndicator() {
           onDismiss = { viewModel.refreshing = false }
        }
    }
}

おわりに

3日目は「無関心な ViewModel」とタイトルでさらにより良い ViewModel について続きを書こうと思います。

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