Created
October 21, 2022 13:57
-
-
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
This file contains hidden or 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
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