1
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?

More than 3 years have passed since last update.

[Android] お寿司屋で例えるAndroid Architecture Compoment :Repository

Posted at

この記事は

前貫までで最終貫を迎えましたが、わたくしの技術力が至らずで上手く実装できていなかったので、続貫になります。
恐らく、永続的に続貫すると思いますw

変更点

今までは、View層の事をお客さんと比喩していましたが、データの出力の責務があるという点でいまいちしっくりこないというフィードバックを頂きました。

確かになぁと思ったので、これからはView層は「お客さん」ではなく「カウンター」として例えていきます。
RemoteDataSource(海)から取得したデータ(魚)を最終的にViewModel(板前)で加工してView(カウンター)に提供するといった感じです。

Repository編

前回は、RepositoryをDaoの事としていました。
今回は、しっかりとRepositoryクラスを作成して定義したいと思います。

とはいえ、Repositoryクラスはそんなに新しい知識は要らないです。
APIを叩いたり、データを保存したり、削除したりするメソッドをView層(カウンター)でもなく、ViewModel(板前)でもなく、Repository(漁師)で定義します。

コードで

こちらで、定義して、、

SushiRepository
class SushiRepository @Inject constructor(
     private val sushiDao: SushiDao
) {
     suspend fun saveSushiData(sushi: Sushi) = withContext(Dispathcers.IO) {
          sushiDao.insertSushi(sushi)
     }

     suspend fun getAllSushiData() = withContext(Dispathers.IO) {
          sushiDao.getAll()
     }
}

こんな感じで呼び出します!

OrderViewModel
@HiltViewModel
class OrderViewModel: ViewModel @Inject constructor(
     private val sushiRepository: SushiRepository
)
     // 省略

    fun hoge() { 
         ViewModelScope.launch {
               sushiRepository.saveSushiData(
                    Sushi(
                         0,
                         _tunaCount.value,
                         calc(_tunaCount)
                    )
          }
     }


Repositoryについて

Repositoryは、お寿司屋の中で漁師の役割があります。
APIデータを魚とした時に、それを取得し、保存したり、削除したりする役割です。

Repositoryで定義したメソッドの返り値が、withContextとなっていましたがこれはメインセーフティを実現するものです。メインセーフティとは、ここではこの関数をバックグラウンドで処理させて、UIの操作を止めないようにするものです。

つまり、コルーチンの実行をIOスレッドに移動させることで、UIの操作を止めることなく非同期処理をすることが出来ます。

終わりに

間違っていたら、ご指摘お願いします!

1
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
1
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?