While developing Android apps, small blocks of repetitive code are frequent. For instance, you might be using a pair of public/private variables in ViewModel to hold the state of all of your domain models.
The major pain comes from this repetitive code, but you can avoid it.
Meet Live Templates
Live Templates are a way to avoid repetitive code in development. All you need is a template and a name, and with it you can quickly add that custom code for the particular case.
Let’s take a look at a ViewModel example. Typically, two variables that represent the state of your resource are expressed as StateFlow (or LiveData)
private val _user = MutableStateFlow<User?>(null
val user: StateFlow<User?> get() = _user)
Let’s create a Live Template for it,
1. Go to File -> Settings (use Ctrl + Alt + S) -> Editor -> Live Templates
2. Select the + (Add) button located on the right side.
3. Write the short name you wish to refer to your template in the abbreviation area, such as `myflow`.
4. Type the following snippet in the template text area.
private val _$VAR$ = kotlinx.coroutines.flow.MutableStateFlow<$TYPE$>(
val $VAR$: kotlinx.coroutines.flow.StateFlow<$TYPE$> get() = _$VAR$)
5. Choose the context by clicking the `Define` button at the bottom and select Kotlin from the list.
Android Studio will now provide you hints to that live template as you write the `myflow` in code editor. Choose it by pressing Enter.
Voila, you have saved 5 precious seconds of your life!!!
Below are some useful Live templates
To create a Composable function having Modifier as the default argument
@androidx.compose.runtime.Composable
fun $NAME$(modifier: androidx.compose.ui.Modifier = androidx.compose.ui.Modifier) {
$END$
}
To create an empty Modifier
modifier: androidx.compose.ui.Modifier = androidx.compose.ui.Modifier