feat(ui): add StationsScreen and StationsViewModel
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
package com.radiola.ui.stations
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.radiola.domain.model.Station
|
||||
import com.radiola.domain.usecase.GetStationsUseCase
|
||||
import com.radiola.domain.usecase.PlayStationUseCase
|
||||
import com.radiola.domain.usecase.ToggleFavoriteUseCase
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.*
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class StationsViewModel @Inject constructor(
|
||||
private val getStationsUseCase: GetStationsUseCase,
|
||||
private val playStationUseCase: PlayStationUseCase,
|
||||
private val toggleFavoriteUseCase: ToggleFavoriteUseCase
|
||||
) : ViewModel() {
|
||||
|
||||
private val _searchQuery = MutableStateFlow("")
|
||||
val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()
|
||||
|
||||
private val _selectedTag = MutableStateFlow<String?>(null)
|
||||
val selectedTag: StateFlow<String?> = _selectedTag.asStateFlow()
|
||||
|
||||
private val _isLoading = MutableStateFlow(false)
|
||||
val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
|
||||
|
||||
private val _error = MutableStateFlow<String?>(null)
|
||||
val error: StateFlow<String?> = _error.asStateFlow()
|
||||
|
||||
val stations: StateFlow<List<Station>> = combine(
|
||||
getStationsUseCase(),
|
||||
_searchQuery,
|
||||
_selectedTag
|
||||
) { allStations, query, tag ->
|
||||
allStations
|
||||
.filter { station ->
|
||||
tag == null || station.tags.contains(tag) || station.genre.equals(tag, ignoreCase = true)
|
||||
}
|
||||
.filter { station ->
|
||||
query.isBlank() ||
|
||||
station.name.contains(query, ignoreCase = true) ||
|
||||
station.genre.contains(query, ignoreCase = true)
|
||||
}
|
||||
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||
|
||||
val tags: StateFlow<List<String>> = getStationsUseCase()
|
||||
.map { stations -> stations.flatMap { it.tags }.distinct().sorted() }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||
|
||||
fun onSearchQueryChange(query: String) {
|
||||
_searchQuery.value = query
|
||||
}
|
||||
|
||||
fun onTagSelected(tag: String?) {
|
||||
_selectedTag.value = tag
|
||||
}
|
||||
|
||||
fun playStation(station: Station) {
|
||||
viewModelScope.launch {
|
||||
playStationUseCase(station)
|
||||
}
|
||||
}
|
||||
|
||||
fun toggleFavorite(station: Station) {
|
||||
viewModelScope.launch {
|
||||
toggleFavoriteUseCase(station)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user