Android Get ViewModel In Fragment

Oct 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) }

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.