Live Templates are a way to avoid repetitive code in development environments like Android Studio or IntelliJ.
When we are writing code, there are times when certain repetitive code can happen, and there is no way to encapsulate it.
For these occasions, Live Templates are an ideal solution that can save you a lot of time.
All you need is a template and a name, and with it you can quickly add that custom code for the particular case.
I will give you the example that you’ll find a lot if you use the Architecture Components, and in particular the MVVM pattern for Android.
Creating Live Templates for LiveData
It happens that when we want to use a
LiveData in a
ViewModel, we usually want to have a modifiable component in order to update its value.
But we are not interested that this value can be modified from the outside. What is recommended is to write a code like this:
private val _message = MutableLiveData<String>() val message: LiveData<String> get() = _message
In this way, we protect that data from being modified from another class that has access to our state.
Check my free guide to create your first project in 15 minutes!
But if you look, there is a lot of repetitive code that we don’t want to repeat every time.
What can we do with
LiveData? Something like this:
If you look, by writing the name of the template and selecting it in the suggestions, we already auto-fill most of the code.
But then it also lets us fill in a couple of gaps: the variable name and the and type. As it is used in both lines, when we write it in one it fills in the next.
How do we do this?
1. Create a new Live Template
To do this go to:
- Settings (Preferences on Mac)
- Live Templates
- Click on “+”
2. Choose the abbreviation
Choose the abbreviation you want. It will appear in the autocomplete when you write it.
You can also put a description to remember what’s it used for:
3. Write the text of the Live Template
Here you will write the code that you don’t want to repeat every time. Write $x$ in the place where you want a variable.
Autofill will stop at that point for you to fill out. If you put the same variable name in other places, its value will be repeated in those places.
In our case we would write:
private val _$VAR$ = MutableLiveData<$TYPE$>() val $VAR$: LiveData<$TYPE$> get() = _$VAR$
4. Choose the context
This indicates the situations in which this live template will be suggested.
In our case we want it for Kotlin code:
And you can already use it!
Live Templates: Conclusion
As you can see, it is very easy to define these live templates, and they can save you from repeating a lot of unnecessary code.
So I encourage you to make your own and share them in the comments section.
If you want a cheatsheet, you can find one of live templates on my Instagram profile.