Skip to content

Instantly share code, notes, and snippets.

@dylangrijalva
Created October 21, 2022 13:57
Show Gist options
  • Save dylangrijalva/dbfab14276ae3479265db63393820bad to your computer and use it in GitHub Desktop.
Save dylangrijalva/dbfab14276ae3479265db63393820bad to your computer and use it in GitHub Desktop.
Creates a queryable state which allows to reuse filter logic in a state with any type of list
typealias QueryPredicate<T> = (String, T) -> Boolean
data class QueryableState<T>(
private val filteredState: StateFlow<List<T>>,
val setQuery: (String) -> Unit
) {
fun state() = filteredState
}
fun <T> ViewModel.createQueryableState(
stateProducer: Flow<List<T>>,
sharingStarted: SharingStarted = SharingStarted.Eagerly,
predicate: QueryPredicate<T>,
): QueryableState<T> {
val queryState = MutableStateFlow("")
val setQuery = { value: String -> queryState.update { value } }
val filteredState = combine(stateProducer, queryState) { state, query ->
if (query.isEmpty()) {
return@combine state
}
state.filter { predicate(query, it) }.toList()
}.stateIn(viewModelScope, sharingStarted, emptyList())
return QueryableState(filteredState, setQuery)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment