Created
May 11, 2020 07:09
-
-
Save alorma/05d0ac6bb000ed28860da4cd550b19cd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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