Skip to content

Instantly share code, notes, and snippets.

@NathanSass
Last active August 5, 2021 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NathanSass/bc8d28e709e6855d8eef7fd6db1b68c8 to your computer and use it in GitHub Desktop.
Save NathanSass/bc8d28e709e6855d8eef7fd6db1b68c8 to your computer and use it in GitHub Desktop.
private suspend fun handleTypeAhead(dataSource: Flow<String>, onChange: (results: List<String>) -> Unit) {
// if a user is typing quickly wait for a pause before collecting most recent update. Ignore anything less then 3 characters.
val resultsFromUser = dataSource.debounce(500).filter { it.length > 3 }
// make an api call to get results for each user's query
// transformLatest will cancel an older api call if a newer arrives first
// this ensures a user will not see typeahead results for an out of date query
val apiCalls = resultsFromUser.transformLatest {
emit(getResultsAsync(it))
}
// pass the queries onto the subscriber. ex. the view to show these updates
apiCalls.collect {
onChange(it)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment