Categories: Kotlin - Android

Why Kotlin extension is preferable to use in android project

As android developers, We are a writing lot of code to make an awesome application. We all know that Android uses Java as a language. In application development, we used many java concepts like thread, singleton classes, etc without knowing the android concept. It may cause memory leaks in Android. I remembered that we have used a lot of boilerplate code in our project, one of them is very popular findViewById(). Now the Google realised that Server-side Java code is not a good fit for android development because android architecture works in a different pattern.

So here Google officially launched the Kotlin is the new primary language a year ago for Android development. The Android community has already welcomed a new programming language in android application development because of its good response and much easier to write the code because it has the similarity of Java API. Kotlin community working hard to make a lot of plugins for Kotlin which makes it easier for a developer to write the code in all patterns. So in this tutorial, we are going to talk about the much-used plugin named Kotlin-Android-extensions.

Start using Kotlin Android Extensions:

Kotlin-android-extensions is now good supported by android studio.

As per the official document

Extensions do not modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.

It means it is just like a static function that can be extended to any other class to use. Another reason for using the extension function is, you don’t have to extend that class to use the methods as if they belong to that class (but not actually part of that class).

Kotlin has provided the plugin to start using in android to extend the functionality of the existing Android API. You need to just add the below plugin as an extension.

apply plugin: 'kotlin-android-extensions'

That’s it. Generally, in android, we are making view visibility and invisibility in many places. We are checking the particular view is visible or not. If it is visible then make this view gone or invisible and vice versa.  In this case, we can create a ViewExtention.kt file to write an extended function to use many places if required. Let’s see an example of check view is visible or not and make then visible and invisible as per requirement.

 

fun View.visible() {
    this.visibility = View.VISIBLE
}

fun View.visible(visible: Boolean) {
    if (visible) {
        visible()
    } else {
        gone()
    }
}

fun View.gone() {
    this.visibility = View.GONE
}

fun View.invisible() {
    this.visibility = View.INVISIBLE
}

fun View.isVisible(): Boolean {
    return visibility == View.VISIBLE
}

fun View.isGone(): Boolean {
    return visibility == View.GONE
}

fun View.isInvisible(): Boolean {
    return visibility == View.INVISIBLE
}

As I remember we used a snack bar to show a message to users like success or error for API call. So we can create an extension function of a snack bar to call multiple places. The best benefit is that we can directly excess this extension function to any Class without using the name of Class.

fun View.snackbar(resId: Int, duration: Int = Snackbar.LENGTH_SHORT) {
    snackbar(this.resources.getString(resId), duration)
}

fun View.snackbar(msg: String, duration: Int = Snackbar.LENGTH_SHORT) {
    Snackbar.make(this, msg, duration).show()
}

fun View.longSnackbar(resId: Int) {
    snackbar(resId, Snackbar.LENGTH_LONG)
}

It is very simple to call in your View Class.

viewError.visible()
            
 textViewError.snackbar("error")

The extension features are not only View Class, but we can also use any Android or Kotlin class or any architecture level like ViewModel. Let’s see an example of loading a list of data in recycler view via API call, So we want to observe MutableLiveData source with the help of LifeCycleOwner to monitor the life cycle change. For that, we can create an extension function that observes the change of Object into a Fragment. Let’s see an example of ViewModelExtention.kt.

fun <T> BaseViewLifecycleFragment.observe(data: MutableLiveData<T>, function: (data: T?) -> Unit) {
    getViewLifecycleOwner1()?.let{
        data.observe(it, android.arch.lifecycle.Observer {
            function(it)
        })
    }
}

We can call this function in our View class to observe the change of MutableLiveData which we have defined in the ViewModel to load the data on the RecyclerView adapter.

  observe(viewModel.movieList, {
            it?.let {
                adapter.dataList = it
            }
            showNoDataFound(adapter.dataList.isEmpty())
        })

You can make many more extension functions with existing Class to add any other function without inheriting. It can access in any class without using the Class Name. We can write much cleaner code to our project like not to use boilerplate code findViewById. We can use the extensions feature to remove this. It is much compatible with any architectural level design like MVVM with Koin dependency Injection and Coroutine for async background calls.

Wrapping 

Now we have a good understanding of the Koin Android extension feature. You can get the complete Github source code of Kotlin MVVM architecture design with Koin and Coroutine. In my next tutorial, we will learn a few more technical stuff, till then enjoy your healthy day.

If you are wondering to learn Android then Please learn from the Android category and wondering to learn Kotlin then Kotlin Category will help you. If you want to learn all the python articles, then learn from the python category.

Please do subscribe to your email to get the newsletter on this blog below and if you like this post then do not forget to share like and comment on the below section.

Happy Coding 🙂

0 0 votes
Article Rating
Why Kotlin extension is preferable to use in android project

Recent Posts

Hide your production API key or any sensitive data in Android

Hi everyone, In this article, we are going to learn how to hide the production… Read More

2 years ago

How to handle the localisation or multi language support in android with examples?

Hello everyone, Today in this article, we are going to learn about localisation to support… Read More

2 years ago

How to convert any callback to Coroutines and use them in Kotlin Android?

Hello everyone, In this article, we are going to learn something to handle the callback… Read More

2 years ago

Request Permission Launcher with Kotlin in Android

In this article, we are learning about the run time permissions for request permission launchers.… Read More

2 years ago

Implement the SMS User Consent API and SMS Retriever API in Android

Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More

3 years ago

Jetpack Compose Coroutine flow with LiveData/ViewModel in Android

Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More

3 years ago