LoginSignup
0
0

無関心な ViewModel

Last updated at Posted at 2023-12-02

はじめに

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

ViewModel について 1日目と2日目の記事の続きになります。

ViewModel から Data Layer への関心をなくそう

Android Developers ガイドの下記の図で示されるように UI Layer である ViewModel から直接 Data Layer への関心をなくしたいです。 ViewModel から Data Layer へのアクセスは Domain Layer に任せます。

UI layer cannot access data layer directly, it must go through the Domain layer

Domain Layer は Optional として UI Layer から直接 Data Layer を参照する方針もあります。

The UI layer's role in app architecture

Good

次のように ViewModel が Data Layer について無関心な状態として、その詳細を Domain Layer に任せたいです。

class LatestNewsViewModel(
    getLatestNewsWithAuthorsUseCase: GetLatestNewsWithAuthorsUseCase
) : ViewModel() {

UseCase が Data Layer に関心を持っている状態にします。

class GetLatestNewsWithAuthorsUseCase(
  private val newsRepository: NewsRepository,
  private val authorsRepository: AuthorsRepository
) { /* ... */ }

具体的な UseCase の書き方については Call use cases in Kotlin の部分で紹介されています。

Bad

ViewModel が Data Layer からどうやって情報を取得するのかその詳細を知りすぎている状態です。

class LatestNewsViewModel(
    private val newsRepository: NewsRepository,
    private val authorsRepository: AuthorsRepository,
) : ViewModel() {

Domain Layer のサンプルとして紹介されている Now in Android App の SearchViewModel は、 UI Layer から Domain Layer と Data Layer へのアクセスが混在した実装になっています。

class SearchViewModel @Inject constructor(
    getSearchContentsUseCase: GetSearchContentsUseCase,
    getSearchContentsCountUseCase: GetSearchContentsCountUseCase,
    recentSearchQueriesUseCase: GetRecentSearchQueriesUseCase,
    private val recentSearchRepository: RecentSearchRepository,
    private val savedStateHandle: SavedStateHandle,
    private val analyticsHelper: AnalyticsHelper,
) : ViewModel() {

おわりに

4日目は @ntsk さんの記事です。

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