@@ -21,42 +21,39 @@ import com.google.samples.apps.nowinandroid.core.model.data.NewsResource
2121import com.google.samples.apps.nowinandroid.core.model.data.SearchResult
2222import com.google.samples.apps.nowinandroid.core.model.data.Topic
2323import kotlinx.coroutines.flow.Flow
24- import kotlinx.coroutines.flow.flow
25- import kotlinx.coroutines.flow.flowOf
24+ import kotlinx.coroutines.flow.MutableStateFlow
25+ import kotlinx.coroutines.flow.combine
26+ import kotlinx.coroutines.flow.update
2627
2728class TestSearchContentsRepository : SearchContentsRepository {
2829
29- private val cachedTopics: MutableList <Topic > = mutableListOf ( )
30- private val cachedNewsResources: MutableList <NewsResource > = mutableListOf ( )
30+ private val cachedTopics = MutableStateFlow (emptyList <Topic >() )
31+ private val cachedNewsResources = MutableStateFlow (emptyList <NewsResource >() )
3132
3233 override suspend fun populateFtsData () = Unit
3334
34- override fun searchContents (searchQuery : String ): Flow <SearchResult > = flowOf(
35- SearchResult (
36- topics = cachedTopics.filter {
37- searchQuery in it.name || searchQuery in it.shortDescription || searchQuery in it.longDescription
38- },
39- newsResources = cachedNewsResources.filter {
40- searchQuery in it.content || searchQuery in it.title
41- },
42- ),
43- )
44-
45- override fun getSearchContentsCount (): Flow <Int > = flow {
46- emit(cachedTopics.size + cachedNewsResources.size)
47- }
35+ override fun searchContents (searchQuery : String ): Flow <SearchResult > =
36+ combine(cachedTopics, cachedNewsResources) { topics, news ->
37+ SearchResult (
38+ topics = topics.filter {
39+ searchQuery in it.name || searchQuery in it.shortDescription || searchQuery in it.longDescription
40+ },
41+ newsResources = news.filter {
42+ searchQuery in it.content || searchQuery in it.title
43+ },
44+ )
45+ }
46+
47+ override fun getSearchContentsCount (): Flow <Int > = combine(cachedTopics, cachedNewsResources) { topics, news -> topics.size + news.size }
4848
4949 /* *
5050 * Test only method to add the topics to the stored list in memory
5151 */
52- fun addTopics (topics : List <Topic >) {
53- cachedTopics.addAll(topics)
54- }
52+ fun addTopics (topics : List <Topic >) = cachedTopics.update { it + topics }
5553
5654 /* *
5755 * Test only method to add the news resources to the stored list in memory
5856 */
59- fun addNewsResources (newsResources : List <NewsResource >) {
60- cachedNewsResources.addAll(newsResources)
61- }
57+ fun addNewsResources (newsResources : List <NewsResource >) =
58+ cachedNewsResources.update { newsResources }
6259}
0 commit comments