forked from technophilist/Musify
-
Notifications
You must be signed in to change notification settings - Fork 3
/
StateProduction.kt
288 lines (264 loc) · 11.5 KB
/
StateProduction.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package com.example.musify.ui.screens.searchscreen
import com.example.musify.data.remote.musicservice.SearchQueryType
import com.example.musify.data.repositories.genresrepository.GenresRepository
import com.example.musify.data.repositories.searchrepository.ContentQuery
import com.example.musify.data.repositories.searchrepository.SearchRepository
import com.example.musify.data.repositories.searchrepository.itemsFor
import com.example.musify.data.tiling.Page
import com.example.musify.data.tiling.toNetworkBackedTiledList
import com.example.musify.data.utils.NetworkMonitor
import com.example.musify.domain.Genre
import com.example.musify.domain.SearchResult
import com.example.musify.domain.SearchResults
import com.example.musify.musicplayer.MusicPlaybackMonitor
import com.example.musify.musicplayer.currentlyPlayingTrackStream
import com.tunjid.mutator.Mutation
import com.tunjid.mutator.coroutines.SuspendingStateHolder
import com.tunjid.mutator.coroutines.actionStateFlowMutator
import com.tunjid.mutator.coroutines.mapToMutation
import com.tunjid.mutator.coroutines.toMutationStream
import com.tunjid.tiler.TiledList
import com.tunjid.tiler.distinctBy
import com.tunjid.tiler.emptyTiledList
import com.tunjid.tiler.map
import com.tunjid.tiler.tiledListOf
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
sealed class SearchAction(val key: String) {
sealed class Searches : SearchAction(key = "Searches") {
data class LoadAround(val contentQuery: ContentQuery?) : Searches()
data class Search(val searchQuery: String) : Searches()
}
data class SearchFilterChange(
val searchFilter: SearchFilter
) : SearchAction(key = "FilterChange")
}
data class SearchUiState(
val isOnline: Boolean = true,
val genres: List<Genre> = emptyList(),
val selectedSearchFilter: SearchFilter = SearchFilter.TRACKS,
val currentlyPlayingTrack: SearchResult.TrackSearchResult? = null,
val contentQueryMap: Map<SearchQueryType, ContentQuery>,
val tiledItems: SearchTiledListFlows = SearchTiledListFlows(
albumTiledListFlow = MutableStateFlow(emptyTiledList()),
artistTiledListFlow = MutableStateFlow(emptyTiledList()),
trackTiledListFlow = MutableStateFlow(emptyTiledList()),
playlistTiledListFlow = MutableStateFlow(emptyTiledList()),
podcastTiledListFlow = MutableStateFlow(emptyTiledList()),
episodeTiledListFlow = MutableStateFlow(emptyTiledList()),
),
)
sealed class SearchItem<out T : SearchResult> {
object Empty : SearchItem<Nothing>()
data class Loaded<T : SearchResult>(val result: T) : SearchItem<T>()
}
val SearchItem<*>.id
get() = when (this) {
SearchItem.Empty -> "Empty"
is SearchItem.Loaded -> result.id
}
val <T : SearchResult> List<SearchItem<T>>.loadedItem: T?
get() = when (val first = firstOrNull()) {
null, SearchItem.Empty -> null
is SearchItem.Loaded -> first.result
}
data class SearchTiledListFlows(
val albumTiledListFlow: StateFlow<TiledList<ContentQuery, SearchItem<SearchResult.AlbumSearchResult>>>,
val artistTiledListFlow: StateFlow<TiledList<ContentQuery, SearchItem<SearchResult.ArtistSearchResult>>>,
val trackTiledListFlow: StateFlow<TiledList<ContentQuery, SearchItem<SearchResult.TrackSearchResult>>>,
val playlistTiledListFlow: StateFlow<TiledList<ContentQuery, SearchItem<SearchResult.PlaylistSearchResult>>>,
val podcastTiledListFlow: StateFlow<TiledList<ContentQuery, SearchItem<SearchResult.PodcastSearchResult>>>,
val episodeTiledListFlow: StateFlow<TiledList<ContentQuery, SearchItem<SearchResult.EpisodeSearchResult>>>,
)
fun CoroutineScope.searchStateProducer(
countryCode: String,
networkMonitor: NetworkMonitor,
musicPlaybackMonitor: MusicPlaybackMonitor,
genresRepository: GenresRepository,
searchRepository: SearchRepository,
) = actionStateFlowMutator<SearchAction, SearchUiState>(
initialState = SearchUiState(
genres = genresRepository.fetchAvailableGenres(),
contentQueryMap = mapSearchQueryTypesTo { searchQueryType ->
searchQueryType.contentQueryFor(
searchQuery = "",
countryCode = countryCode
)
}
),
inputs = listOf(
networkMonitor.isOnlineMutations(),
musicPlaybackMonitor.playingTrackMutations(),
),
actionTransform = { actions ->
actions.toMutationStream(keySelector = SearchAction::key) {
when (val action = type()) {
is SearchAction.Searches -> action.flow.searchMutations(
countryCode = countryCode,
scope = this@searchStateProducer,
searchRepository = searchRepository,
)
is SearchAction.SearchFilterChange -> action.flow.searchFilterMutations()
}
}
}
)
private fun NetworkMonitor.isOnlineMutations(): Flow<Mutation<SearchUiState>> =
isOnline.mapToMutation {
copy(isOnline = it)
}
private fun MusicPlaybackMonitor.playingTrackMutations(): Flow<Mutation<SearchUiState>> =
currentlyPlayingTrackStream.mapToMutation {
copy(currentlyPlayingTrack = it)
}
private fun Flow<SearchAction.SearchFilterChange>.searchFilterMutations(): Flow<Mutation<SearchUiState>> =
mapToMutation {
copy(selectedSearchFilter = it.searchFilter)
}
context(SuspendingStateHolder<SearchUiState>)
private fun Flow<SearchAction.Searches>.searchMutations(
countryCode: String,
scope: CoroutineScope,
searchRepository: SearchRepository
): Flow<Mutation<SearchUiState>> = flow {
val initialState = state()
// Restore queries from last session
val queryTypeToQueryStateFlow = mapSearchQueryTypesTo {
MutableStateFlow(initialState.contentQueryMap.getValue(it))
}
// Emit the tiled item state flows first
emit {
copy(
tiledItems = SearchTiledListFlows(
albumTiledListFlow = queryTypeToQueryStateFlow
.getValue(SearchQueryType.ALBUM)
.toTiledList(
scope = scope,
initialValue = initialState.tiledItems.albumTiledListFlow.value,
searchRepository = searchRepository
),
artistTiledListFlow = queryTypeToQueryStateFlow
.getValue(SearchQueryType.ARTIST)
.toTiledList(
scope = scope,
initialValue = initialState.tiledItems.artistTiledListFlow.value,
searchRepository = searchRepository
),
trackTiledListFlow = queryTypeToQueryStateFlow
.getValue(SearchQueryType.TRACK)
.toTiledList(
scope = scope,
initialValue = initialState.tiledItems.trackTiledListFlow.value,
searchRepository = searchRepository
),
playlistTiledListFlow = queryTypeToQueryStateFlow
.getValue(SearchQueryType.PLAYLIST)
.toTiledList(
scope = scope,
initialValue = initialState.tiledItems.playlistTiledListFlow.value,
searchRepository = searchRepository
),
podcastTiledListFlow = queryTypeToQueryStateFlow
.getValue(SearchQueryType.SHOW)
.toTiledList(
scope = scope,
initialValue = initialState.tiledItems.podcastTiledListFlow.value,
searchRepository = searchRepository
),
episodeTiledListFlow = queryTypeToQueryStateFlow
.getValue(SearchQueryType.EPISODE)
.toTiledList(
scope = scope,
initialValue = initialState.tiledItems.episodeTiledListFlow.value,
searchRepository = searchRepository
)
)
)
}
// Collect from the backing flow and update searches as appropriate
collect { action ->
when (action) {
is SearchAction.Searches.LoadAround -> when (val type = action.contentQuery?.type) {
null -> Unit
else -> {
queryTypeToQueryStateFlow.getValue(type).value = action.contentQuery
// Update UI state with the latest query
emit { copy(contentQueryMap = contentQueryMap + (type to action.contentQuery)) }
}
}
// Only pages in the pager will have their search queries executed, but the queries
// for offscreen pages will be saved to begin execution when they're visible
is SearchAction.Searches.Search -> {
val newContentQueryMap = mapSearchQueryTypesTo { searchQueryType ->
searchQueryType.contentQueryFor(
searchQuery = action.searchQuery,
countryCode = countryCode
)
}
queryTypeToQueryStateFlow.forEach { (type, stateFlow) ->
stateFlow.value = newContentQueryMap.getValue(type)
}
// Update UI state with the latest queries
emit { copy(contentQueryMap = newContentQueryMap) }
}
}
}
}
private inline fun <reified T : SearchResult> MutableStateFlow<ContentQuery>.toTiledList(
scope: CoroutineScope,
initialValue: TiledList<ContentQuery, SearchItem<T>>,
searchRepository: SearchRepository
): StateFlow<TiledList<ContentQuery, SearchItem<T>>> {
val startPage = value.page
return debounce {
// Don't debounce the If its the first character or more is being loaded
if (it.searchQuery.length < 2 || it.page.offset != startPage.offset) 0
// Debounce for key input
else 300
}.toNetworkBackedTiledList(
startQuery = value
) { query ->
if (query.searchQuery.isEmpty()) emptyFlow()
else searchRepository.searchFor(query)
.map<SearchResults, List<T>>(SearchResults::itemsFor)
}
.map { tiledItems ->
if (tiledItems.isEmpty()) tiledListOf(value to SearchItem.Empty)
else tiledItems
.distinctBy(SearchResult::id)
.map { SearchItem.Loaded(it) }
}
.debounce { tiledItems ->
// If empty, the search query might have just changed.
// Allow items to be fetched for item position animations
if (tiledItems.first() is SearchItem.Empty) 350L
else 0L
}
.stateIn(
scope = scope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = initialValue
)
}
private fun SearchQueryType.contentQueryFor(
searchQuery: String,
countryCode: String,
) = ContentQuery(
type = this,
searchQuery = searchQuery,
page = Page(offset = 0),
countryCode = countryCode
)
fun <T> mapSearchQueryTypesTo(mapper: (SearchQueryType) -> T) =
SearchQueryType.values().associateBy(
keySelector = { it },
valueTransform = mapper
)