Debounce for android button clicks via bindingAdapter

@BindingAdapter("android:onClick")
fun setDebounceListener(view: Button, onClickListener: View.OnClickListener) {
val scope = ViewTreeLifecycleOwner.get(view)!!.lifecycleScope
val clickWithDebounce: (view: View) -> Unit =
debounce(scope = scope) {
onClickListener.onClick(it)
}

view.setOnClickListener(clickWithDebounce)
}


fun <T> debounce(
delayMillis: Long = 300L,
scope: CoroutineScope,
action: (T) -> Unit
): (T) -> Unit {
var debounceJob: Job? = null
return { param: T ->
if (debounceJob == null) {
debounceJob = scope.launch {
action(param)
delay(delayMillis)
debounceJob = null
}
}
}
}

Usage :

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{ () -> activity.youOnClickCallbackHere()}"
android:text="Click with debounce" />

--

--

Having multiple products flavors in android project can take it toll over build time. Below is the pro tip to force gradle to build only your desired build.

in your app.gradle

android{

….

if (project.rootProject.file('dev.props').exists()) {
def devProps = new Properties()
devProps.load(project.rootProject.file('dev.props').newDataInputStream())
def currentDevFlavor = devProps.DEV_FLAVOR

project.logger.lifecycle('preffered falvour ===>' + currentDevFlavor)

android.variantFilter { variant ->

def flavorName = variant.getFlavors().get(0).name +
variant.getFlavors().get(1).name + buildType.name

project.logger.lifecycle('Variant Flavor Name ==>' + flavorName)

if (currentDevFlavor && (flavorName != currentDevFlavor)) {
project.logger.lifecycle('Ignoring ==>' + flavorName)
variant.setIgnore(true)
} else {
project.logger.lifecycle("Building..===>" + currentDevFlavor)
}
}
}

}

and create one file namely dev.props and add below line to it

DEV_FLAVOR= myappdevdebug //name of your desired build flavour with dimension

--

--

Balwinder Singh Rajput

Balwinder Singh Rajput

Hi there 👋 Namaste 🙏🏻 .👨‍💻 developing apps from 10+ years. 👨‍🏫 IoT | E-commerce | baking domain expert.