Skip to content

Instantly share code, notes, and snippets.

@alorma
Created May 11, 2020
Embed
What would you like to do?
class SearchStoresMapViewModel(
private val storeCache: StoreCache,
private val mapper: StoreUiMapper
) : ViewModel() {
private val appliedFilters: MutableSet<OpenStatus> = mutableSetOf()
private val filtersChannel = BroadcastChannel<Set<OpenStatus>>(Channel.CONFLATED)
private val queryChannel = BroadcastChannel<String>(Channel.CONFLATED)
private val _stores: LiveData<List<StoreUI>> = filtersChannel.asFlow()
.combine(queryChannel.asFlow().onEach { delay(400) }) { text, filters -> text to filters }
.map { (filters: Set<OpenStatus>, text: String) -> searchStores(text, filters) }
.map { stores: List<Store> -> mapper.map(stores) }
.asLiveData()
private fun searchStores(text: String, filters: Set<OpenStatus>): List<Store> =
storeCache.getByStatus(filters).filter { store ->
filterStoresByText(text, store)
}
private fun filterStoresByText(
text: String,
store: Store
): Boolean = if (text.isBlank()) {
true
} else {
store.name.contains(text, true)
}
val stores: LiveData<List<StoreUI>>
get() = _stores
init {
viewModelScope.launch {
queryChannel.send("")
filtersChannel.send(appliedFilters)
}
}
fun search(text: String? = "") {
viewModelScope.launch { queryChannel.send(text.orEmpty()) }
}
fun onFilterChanged(status: OpenStatus, checked: Boolean) {
if (checked) {
appliedFilters.add(status)
} else {
appliedFilters.remove(status)
}
viewModelScope.launch { filtersChannel.send(appliedFilters) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment