[코틀린] ViewModel

ViewModel

Add dependency

val lifecycle_version = "2.4.0-beta01"

// ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")

Get Instance

//1.
	val viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
//Additional dependency(lifecycle extention) needed.
//-> implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

//2
	val viewModel : MainViewModel by viewModels()
//Additional dependency(activity-ktx or fragment-ktx) needed.
//-> implementation("androidx.activity:activity-ktx:$activity_version")
//Check source compatibility & target compatibility (1.8 or over).
//File > Project structure > Modules에서 설정가능.
//-> 설정을 바꾸면 build.gradle에서 아래와 같이 설정된다.
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
//추가적으로 compileOptions과 같은 레벨에 아래 코드를 추가한다.
    kotlinOptions {
        jvmTarget = '1.8'
    }