|
17 | 17 |
|
18 | 18 | package com.example.android.devbyteviewer.repository
|
19 | 19 |
|
20 |
| -// TODO (01) Create a VideosRepository class that takes a VideosDatabase argument. |
| 20 | +import androidx.lifecycle.LiveData |
| 21 | +import androidx.lifecycle.Transformations |
| 22 | +import com.example.android.devbyteviewer.database.VideosDatabase |
| 23 | +import com.example.android.devbyteviewer.database.asDomainModel |
| 24 | +import com.example.android.devbyteviewer.domain.Video |
| 25 | +import com.example.android.devbyteviewer.network.Network |
| 26 | +import com.example.android.devbyteviewer.network.asDatabaseModel |
| 27 | +import kotlinx.coroutines.Dispatchers |
| 28 | +import kotlinx.coroutines.withContext |
21 | 29 |
|
22 |
| -// TODO (02) Define a suspend refreshVideos() function that gets data from the network and |
23 |
| -// inserts it into the database. |
| 30 | +class VideosRepository(private val database: VideosDatabase) { |
24 | 31 |
|
25 |
| -// TODO (03) Define a Transformations.map to convert the DatabaseVideo list to a list of Video. |
| 32 | + /** |
| 33 | + * A playlist of videos that can be shown on the screen. |
| 34 | + */ |
| 35 | + val videos: LiveData<List<Video>> = |
| 36 | + Transformations.map(database.videoDao.getVideos()) { |
| 37 | + it.asDomainModel() |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Refresh the videos stored in the offline cache. |
| 42 | + * |
| 43 | + * This function uses the IO dispatcher to ensure the database insert database operation |
| 44 | + * happens on the IO dispatcher. By switching to the IO dispatcher using `withContext` this |
| 45 | + * function is now safe to call from any thread including the Main thread. |
| 46 | + * |
| 47 | + * To actually load the videos for use, observe [videos] |
| 48 | + */ |
| 49 | + suspend fun refreshVideos() { |
| 50 | + withContext(Dispatchers.IO) { |
| 51 | + val playlist = Network.devbytes.getPlaylist().await() |
| 52 | + database.videoDao.insertAll(*playlist.asDatabaseModel()) |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments