Debounce Operator in Android
Siddhant Mishra
Senior Android Developer at Teachmint | Kotlin and Java | DSA - 300+ on Leetcode | I read and write about Android and DSA
Today I will be writing about a concept I came across and got an opportunity to implement the same in my sample Android project.
The topic for today is Debounce Operator and its usage in Android.
First of all debouncing is a programatic concept that is deployed to prevent unleashing the time and resource intensive tasks too frequently in our application which can in turn lead to unresponsive and laggy behaviour in our application.
Now in debounce we initiate a task and then wait for a certain time for the user to take an action and if the user does not perform any new tasks in that period, then we perform further action using the user input.
In contrast if the user performs a new action in between(within the debounce time), we start the debounce timer afresh(i.e from 0) again and wait for the next user actions before processing the user input further.
领英推荐
Recently I got an opportunity to implement the debounce operator in an Instant Search function I implemented in my project, where the user is expected to type each character quite frequently and we need not fire a fresh api call for each input rather wait for the user to enter the entire keyword before making the necessary api call. Please refer below code for the sample code.
private fun makeApiCall() {
viewModelScope.launch {
query.debounce(DEBOUNCE_TIMER)
// Do whatever you want to do with the entered input
}
}
Now regarding the debounce timer, we can choose an optimal time for our use case, keeping it too high might feel unresponsive to the user whereas keeping it too low might make too many unecessary api calls.
I hope we got to know about the functionality of debouce operator in Android.
Thanks for reading !
Business Development Manger
1 年The Art & Science of Secure Software Development Get Your FREE Copy Today: https://tinyurl.com/5n8dhnrx #softwaredevelopment #software #development #securesoftwaredevelopment