Skip to content

Commit df63328

Browse files
author
Jill Heske
committed
Step.05-Solution-Build-a-Repository
1 parent cda4edb commit df63328

File tree

1 file changed

+34
-4
lines changed

1 file changed

+34
-4
lines changed

app/src/main/java/com/example/android/devbyteviewer/repository/VideosRepository.kt

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,39 @@
1717

1818
package com.example.android.devbyteviewer.repository
1919

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
2129

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) {
2431

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

Comments
 (0)