Last active
August 5, 2021 11:23
-
-
Save NathanSass/bc8d28e709e6855d8eef7fd6db1b68c8 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
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