@@ -21,42 +21,36 @@ 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
27+ import org.jetbrains.annotations.TestOnly
2628
2729class TestSearchContentsRepository : SearchContentsRepository {
2830
29- private val cachedTopics: MutableList <Topic > = mutableListOf ( )
30- private val cachedNewsResources: MutableList <NewsResource > = mutableListOf ( )
31+ private val cachedTopics = MutableStateFlow (emptyList <Topic >() )
32+ private val cachedNewsResources = MutableStateFlow (emptyList <NewsResource >() )
3133
3234 override suspend fun populateFtsData () = Unit
3335
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- }
48-
49- /* *
50- * Test only method to add the topics to the stored list in memory
51- */
52- fun addTopics (topics : List <Topic >) {
53- cachedTopics.addAll(topics)
54- }
55-
56- /* *
57- * Test only method to add the news resources to the stored list in memory
58- */
59- fun addNewsResources (newsResources : List <NewsResource >) {
60- cachedNewsResources.addAll(newsResources)
61- }
36+ override fun searchContents (searchQuery : String ): Flow <SearchResult > =
37+ combine(cachedTopics, cachedNewsResources) { topics, news ->
38+ SearchResult (
39+ topics = topics.filter {
40+ searchQuery in it.name || searchQuery in it.shortDescription || searchQuery in it.longDescription
41+ },
42+ newsResources = news.filter {
43+ searchQuery in it.content || searchQuery in it.title
44+ },
45+ )
46+ }
47+
48+ override fun getSearchContentsCount (): Flow <Int > = combine(cachedTopics, cachedNewsResources) { topics, news -> topics.size + news.size }
49+
50+ @TestOnly
51+ fun addTopics (topics : List <Topic >) = cachedTopics.update { it + topics }
52+
53+ @TestOnly
54+ fun addNewsResources (newsResources : List <NewsResource >) =
55+ cachedNewsResources.update { it + newsResources }
6256}
0 commit comments