As Kotlin quickly becomes popular with Android developers, more and more tools and APIs are being released to be more productive while creating Android apps.
Google announced many new features on Google IO 2019 around Kotlin and Android – here are some of the highlights.
Earlier, when you used Android Studio templates to create a new activity or other Android component, would create it in Java first, then you had to use the function Convert to Kotlin for to switch it to Kotlin.
In the latest version of Android Studio, it can generate new activities or fragments in Java or Kotlin.
You can select the language it uses in New Android Activity or New Android Component wizard.
Read more about it on the Android Developer page.
Coroutines for all the things
Google recently added support for coroutines in many Jetpack components.
Instead of expanding
Worker class for use with
WorkManager you can now expand
This class gives you access to the suspension function
doWork () performed on a
Dispatchers coroutine context of your choice.
Read more on the WorkManager documentation.
Starting in room 2.1
All methods in your DAO interfaces can
suspendfunctions, and Room's generated code will support it.
For easy database operation, the Room handles the thread and ensures that it uses a background thread (currently IO
For more complicated operations, you can specify which
Dispatcheryou want the operations to perform. Florina Muntenescu from Google has a more detailed message about this.
Lifecycle, LiveData and ViewModel
Life cycle conscious Jetpack components also have coroutine support now.
ViewModel create coroutine scopes (
ViewModelScope ), and any coroutine initiated within these ranges is automatically interrupted when its scope is done.
Lifecycle s, this is when it is corrupted and for
ViewModel s it is when it is deleted.
This makes it easier to handle life-cycle-dependent work with coroutines.
LiveData can also be generated by co-routines in a life-cycle dependent manner using the [Live Data] builder function, which allows you to call suspended functions that output their results in
Read more about life-cycle-dependent coral support on developer documentation.
KTX – Android API Extensions
Last year around IO 2018, Google launched the release of the beta by KTX, a huge set of libaries that include expansion features for Android components.
Many of these now have stable versions, and new libraries for various components are still added.
These are useful for writing regular Android operations with an idiotic Kotlin syntax.
In general, KTX enables the use of lambdas to allow the different APIs to use slightly smaller boiler plates.
For example, fragment transactions can be simplified:
// without ktx
. Initial Transaction ()
. addToBackStack ( "FragmentName" )
. ( R] ] [fragment] container [fragment] [fragment] )
. commits ();
// with ktx
getSupportFragmentManager (). addToBackStack ( "FragmentName" )