From the course: Android Development Essential Training: Manage Data with Kotlin

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Pass data in a shared ViewModel

Pass data in a shared ViewModel

From the course: Android Development Essential Training: Manage Data with Kotlin

Start my 1-month free trial

Pass data in a shared ViewModel

- [Instructor] There are a few different ways to pass data between fragments. In an earlier course dedicated to the use of the navigation component, I described how to define arguments in a fragment. You can set the type to one of the simple types, or to something called a parcelable object. But there's a much easier way to do this when you use the View Model Architecture. You can pass data between fragments by having them share a single view model component. A primary fragment can place data in the view model, and then navigate to a secondary fragment. That fragment can then retrieve the data from the same view model instance. This approach is easy to code, and easy to maintain over time. I'll go to my MainViewModel class, and I'm going to change its name to reflect how I'm going to use it. I'll click into the class name and press Shift F6, and change the name of the class to SharedViewModel. Then I'll change its location in my code. I'll go to my UI package, and I'll create a new…

Contents