Skip to content

androidx.activity:activity-ktx

Official Description: Kotlin extensions for 'activity' artifact

CommonsWare's Notes

The primary thing that we get from this package is the viewmodels() extension function. Technically this is on ComponentActivity from the androidx.activity:activity artifact, though in practice you will use it mostly from FragmentActivity, AppCompatActivity, and similar classes.

viewmodels() is a property delegate, allowing you to use syntax like:

class MainActivity : AppCompatActivity() {
    val viewmodel: MainViewModel by viewmodels()
}

Then, when you first access viewmodel, the delegate will look up the ViewModel for you, so you can avoid the ViewModelProviders.of() statement and a lateinit var, the way we normally get a ViewModel.

However, be careful: just because this is now encapuslated in a property delegate does not change the timing rules. Do not attempt to reference your ViewModel property until onCreate() — in particular, do not try to reference it from another property initializer.

Documentation

Versions