Boost your Android Development Process with these awesome Kotlin extensions
Kotlin provides the ability to extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator
Extension is one of my favourite feature on Kotlin, with Kotlin extension we have more control to add function or property to an object / class without have to inherit it class, even we can add new function into final class. Extension not only change the way how android developers write helpers or utils function, more than it, it already changes how developers write it code overall.
Android Jetpack already launch KTX to make android developer write less code by add many extension function that help developer to write less code and less boilerplate. But sure extension still have many hidden potential to help us boost our development process, so here is some awesome Kotlin extension that can help make your project greater.
Generic
Checking nullability
Usage :
Add zero as default number value
Usage :
Add default value if variable is null
This extension is likely orEmpty()
or orZero()
extension but with more customizable value
Usage :
Live Data
Observe Live Data
Comparison and usage :
Glide / Picasso
Load Image
Glide or Picasso is popular library for image loader, most of us use image loader library to load image from url instead of handle download and caching it manually.
We can add extension function to load image from url like this :
Comparison and usage :
Sure, you can add more preprocessing or callback on this loadImage
extension.
View
Throttle / Debounce Click
As Android Developer, we must be familiar with setOnClickListener
that listen all view click event, but did you know that there are many hidden bug that lead to unexpected app behaviour when we don’t handle this click event properly.
For example : When user need click action to create new order, user can simply doing rapid click to order button that will impact calling order usecase twice, it will make our app create double order.
With this extension, we can simply avoid this kind of scenario or another unexpected scenario because of double click. This extension will give time to our view to not response another click input from user.
Usage :
View Visibility
Here is some simple but useful to handle view visibility :
Thank you
Reference :
Other article about mobile development :