Android Get ViewModel In Fragment

October 1, 2019

Basic

class HomeFragment : Fragment() {
    private lateinit var viewModel: HomeViewModel
    private lateinit var mainViewModel: MainViewModel

    // or super.onActivityCreated
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)
        mainViewModel = activity?.run {
            ViewModelProviders.of(this).get(MainViewModel::class.java)
        } ?: throw Exception("Invalid Activity")
    }
}

via KTX

depedencies {
    // implementation "androidx.activity:activity-ktx:1.1.0"
    implementation "androidx.fragment:fragment-ktx:1.1.0"
}
class HomeFragment : Fragment() {
    private val viewModel by viewModels<HomeViewModel>()
    private val mainViewModel by activityViewModels<MainViewModel>()

}

via Dagger2 and ViewModelFactory

Refer Setup Dagger 2 For Android Kotlin

with Saved State

Saved State module for ViewModel

depedencies {
    implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha05'
}
val viewModel = ViewModelProvider(this, SavedStateVMFactory(this)).get(SavedStateViewModel::class.java)

via KTX

private val viewModel by viewModels { SavedStateVMFactory(this) }
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.