Is there any fancy way to implement debounce
logic with Kotlin Android?
I'm not using Rx in project.
There is a way in Java, but it is too big as for me here.
Is there any fancy way to implement debounce
logic with Kotlin Android?
I'm not using Rx in project.
There is a way in Java, but it is too big as for me here.
I've created a gist with three debounce operators inspired by this elegant solution from Patrick where I added two more similar cases: throttleFirst
and throttleLatest
. Both of these are very similar to their RxJava analogues (throttleFirst, throttleLatest).
throttleLatest
works similar to debounce
but it operates on time intervals and returns the latest data for each one, which allows you to get and process intermediate data if you need to.
fun <T> throttleLatest(
intervalMs: Long = 300L,
coroutineScope: CoroutineScope,
destinationFunction: (T) -> Unit
): (T) -> Unit {
var throttleJob: Job? = null
var latestParam: T
return { param: T ->
latestParam = param
if (throttleJob?.isCompleted != false) {
throttleJob = coroutineScope.launch {
delay(intervalMs)
latestParam.let(destinationFunction)
}
}
}
}
throttleFirst
is useful when you need to process the first call right away and then skip subsequent calls for some time to avoid undesired behavior (avoid starting two identical activities on Android, for example).
fun <T> throttleFirst(
skipMs: Long = 300L,
coroutineScope: CoroutineScope,
destinationFunction: (T) -> Unit
): (T) -> Unit {
var throttleJob: Job? = null
return { param: T ->
if (throttleJob?.isCompleted != false) {
throttleJob = coroutineScope.launch {
destinationFunction(param)
delay(skipMs)
}
}
}
}
debounce
helps to detect the state when no new data is submitted for some time, effectively allowing you to process a data when the input is completed.
fun <T> debounce(
waitMs: Long = 300L,
coroutineScope: CoroutineScope,
destinationFunction: (T) -> Unit
): (T) -> Unit {
var debounceJob: Job? = null
return { param: T ->
debounceJob?.cancel()
debounceJob = coroutineScope.launch {
delay(waitMs)
destinationFunction(param)
}
}
}
All these operators can be used as follows:
val onEmailChange: (String) -> Unit = throttleLatest(
300L,
viewLifecycleOwner.lifecycleScope,
viewModel::onEmailChanged
)
emailView.onTextChanged(onEmailChange)
For a simple approach from inside a ViewModel
, you can just launch a job within the viewModelScope
, keep track of the job, and cancel it if a new value arises before the job is complete:
private var searchJob: Job? = null
fun searchDebounced(searchText: String) {
searchJob?.cancel()
searchJob = viewModelScope.launch {
delay(500)
search(searchText)
}
}
I use a callbackFlow and debounce from Kotlin Coroutines to achieve debouncing. For example, to achieve debouncing of a button click event, you do the following:
Create an extension method on Button
to produce a callbackFlow
:
fun Button.onClicked() = callbackFlow<Unit> {
setOnClickListener { offer(Unit) }
awaitClose { setOnClickListener(null) }
}
Subscribe to the events within your life-cycle aware activity or fragment. The following snippet debounces click events every 250ms:
buttonFoo
.onClicked()
.debounce(250)
.onEach { doSomethingRadical() }
.launchIn(lifecycleScope)
A more simple and generic solution is to use a function that returns a function that does the debounce logic, and store that in a val.
fun <T> debounce(delayMs: Long = 500L,
coroutineContext: CoroutineContext,
f: (T) -> Unit): (T) -> Unit {
var debounceJob: Job? = null
return { param: T ->
if (debounceJob?.isCompleted != false) {
debounceJob = CoroutineScope(coroutineContext).launch {
delay(delayMs)
f(param)
}
}
}
}
Now it can be used with:
val handleClickEventsDebounced = debounce<Unit>(500, coroutineContext) {
doStuff()
}
fun initViews() {
myButton.setOnClickListener { handleClickEventsDebounced(Unit) }
}
I have created a single extension function from the old answers of stack overflow:
fun View.clickWithDebounce(debounceTime: Long = 600L, action: () -> Unit) {
this.setOnClickListener(object : View.OnClickListener {
private var lastClickTime: Long = 0
override fun onClick(v: View) {
if (SystemClock.elapsedRealtime() - lastClickTime < debounceTime) return
else action()
lastClickTime = SystemClock.elapsedRealtime()
}
})
}
View onClick using below code:
buttonShare.clickWithDebounce {
// Do anything you want
}
Thanks to https://medium.com/@pro100svitlo/edittext-debounce-with-kotlin-coroutines-fd134d54f4e9 and https://stackoverflow.com/a/50007453/2914140 I wrote this code:
private var textChangedJob: Job? = null
private lateinit var textListener: TextWatcher
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
textListener = object : TextWatcher {
private var searchFor = "" // Or view.editText.text.toString()
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val searchText = s.toString().trim()
if (searchText != searchFor) {
searchFor = searchText
textChangedJob?.cancel()
textChangedJob = launch(Dispatchers.Main) {
delay(500L)
if (searchText == searchFor) {
loadList(searchText)
}
}
}
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
editText.setText("")
loadList("")
}
override fun onResume() {
super.onResume()
editText.addTextChangedListener(textListener)
}
override fun onPause() {
editText.removeTextChangedListener(textListener)
super.onPause()
}
override fun onDestroy() {
textChangedJob?.cancel()
super.onDestroy()
}
I didn't include coroutineContext
here, so it probably won't work, if not set. For information see Migrate to Kotlin coroutines in Android with Kotlin 1.3.
You can use kotlin coroutines to achieve that. Here is an example.
Be aware that coroutines are experimental at kotlin 1.1+ and it may be changed in upcoming kotlin versions.
Since Kotlin 1.3 release, coroutines are now stable.
Using tags seems to be a more reliable way especially when working with RecyclerView.ViewHolder
views.
e.g.
fun View.debounceClick(debounceTime: Long = 1000L, action: () -> Unit) {
setOnClickListener {
when {
tag != null && (tag as Long) > System.currentTimeMillis() -> return@setOnClickListener
else -> {
tag = System.currentTimeMillis() + debounceTime
action()
}
}
}
}
Usage:
debounceClick {
// code block...
}
@masterwork,
Great answer. This is my implementation for a dynamic searchbar with an EditText. This provides great performance improvements so the search query is not performed immediately on user text input.
fun AppCompatEditText.textInputAsFlow() = callbackFlow {
val watcher: TextWatcher = doOnTextChanged { textInput: CharSequence?, _, _, _ ->
offer(textInput)
}
awaitClose { this@textInputAsFlow.removeTextChangedListener(watcher) }
}
searchEditText
.textInputAsFlow()
.map {
val searchBarIsEmpty: Boolean = it.isNullOrBlank()
searchIcon.isVisible = searchBarIsEmpty
clearTextIcon.isVisible = !searchBarIsEmpty
viewModel.isLoading.value = true
return@map it
}
.debounce(750) // delay to prevent searching immediately on every character input
.onEach {
viewModel.filterPodcastsAndEpisodes(it.toString())
viewModel.latestSearch.value = it.toString()
viewModel.activeSearch.value = !it.isNullOrBlank()
viewModel.isLoading.value = false
}
.launchIn(lifecycleScope)
}
@masterwork's answer worked perfectly fine. Here it is for ImageButton with compiler warnings removed:
@ExperimentalCoroutinesApi // This is still experimental API
fun ImageButton.onClicked() = callbackFlow<Unit> {
setOnClickListener { offer(Unit) }
awaitClose { setOnClickListener(null) }
}
// Listener for button
val someButton = someView.findViewById<ImageButton>(R.id.some_button)
someButton
.onClicked()
.debounce(500) // 500ms debounce time
.onEach {
clickAction()
}
.launchIn(lifecycleScope)
object ActionDelayer {
var isActionTriggered = false
fun delay(milliseconds: Long = 10000, scope: CoroutineScope = CoroutineScope(Dispatchers.IO), action: () -> Unit) {
if (!isActionTriggered) {
scope.launch {
action()
isActionTriggered = true
Executors.newSingleThreadScheduledExecutor().schedule({
isActionTriggered = false
}, milliseconds, TimeUnit.MILLISECONDS)
}
}
}
}
Usage:
ActionDelayer.delay { println("Repeating...") }
Tested. This works for me.
object DebounceHelper {
private var job: Job? = null
fun <T> debounce(
delayMs: Long = 500L,
scope: CoroutineScope,
func: (T) -> Unit
): (T) -> Unit {
job?.cancel()
return { param: T ->
job = scope.launch {
delay(delayMs)
func(param)
}
}
}
}
DebounceHelper.debounce<Unit>(2000, scope) {
anotherFunc()
}.invoke(Unit)
If anyone needs more easy kotlin extension here it is
fun EditText.debounce(delay: Long, action: (CharSequence?) -> Unit) {
doAfterTextChanged { text ->
val counter = getTag(id) as? Int ?: 0
handler.removeCallbacksAndMessages(counter)
handler.postDelayed(delay, ++counter) { action(text) }
setTag(id, counter)
}
}
Uses
val editText = findViewById<EditText>(R.id.editText)
editText.debounce(500) {
if (it.isNotEmpty()) {
// Submit the form
}
}