Android ViewModel (Kotlin)

February 27, 2019

ViewModel.

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

Dependencies.

dependencies {
    def lifecycle_version = "2.0.0"

    // ViewModel and LiveData
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    // alternatively - just ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    // alternatively - just LiveData
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"    

    kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

    // optional - Test helpers for LiveData
    testImplementation "androidx.arch.core:core-testing:$lifecycle_version"    
}

NOTE: One of my latest project seems to include androidx.lifecycle.* libraries without explicitly importing them, perhaps some google libraries included them as depedencies.

Activity

class MainActivity : AppCompatActivity() {

    private lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
    }
}

ViewModel

class MainViewModel : ViewModel() {
    internal var lastActiveFragmentTag: String? = null
}

NOTE: You might be interested to use Dagger2 with ViewModel.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.