Using a ViewModel3:39 with Ben Deitch
In this video we'll use a ViewModel to persist instance state across a rotation!This syllabus doesn't have any learning objectives.
We've just got access to our ViewModel, now it's time to start using it. 0:00 Let's start by updating the activities ui based on what's in the ViewModel. 0:05 To update the name of the pizza, we just need to change the title of the activity. 0:10 On the line after our ViewModel, 0:15 let's set title=viewModel.pizzaName. 0:18 Next, we need to update the pizza based on what's in the view model. 0:24 To do this, instead of passing an empty map to our pizzaView, 0:28 let's pass in viewModel.switchStates. 0:33 Great! 0:37 Now that we've updated the ui based on the viewModel, 0:38 we just need to update the viewModel whenever the ui changes. 0:41 When a user gives a pizza a new name, it triggers this code down here. 0:46 Which makes sure there's actually some text and 0:53 the edit text, and then updates the activities title. 0:57 Let's add a line below that and also update our view model, 1:01 viewModel.pizzaName =_text. 1:05 Perfect, all that's left is updating the switches based on the viewModel and 1:11 updating the viewModel whenever a switch is switched. 1:15 To do this since those actions take place in creator adapter, 1:19 we'll need to pass along our viewModel to creator adapter. 1:23 Let's add our viewModel as the second parameter to creator adapter up inside of 1:27 onCreate. 1:32 Then let's use Alt+Enter to add this parameter to the constructor, 1:35 And choose for it to be a vowel, then we hit Refactor, and 1:42 let's open Creator Adaptor. 1:47 And now that we've got our view model as a variable, 1:50 let's use it in the updateView function to update the switches. 1:53 Below where we update that text, 1:57 let's add a new line instead of switch.isChecked = 2:00 _viewModel.switchStates and then pass in the topping. 2:05 Then it's telling us that it's looking for a boolean, but 2:13 it's found a boolean that might be null. 2:17 So let's use the Elvis operator to give it a fallback value. 2:20 At the end of the line, add a space, then a question mark and 2:25 a colon, then another space, and type false. 2:30 And now if this value is ever null, we'll just get false instead. 2:34 Last but not least, when a switch is switched, 2:39 we need to update the view model instead of the pizza toppings list. 2:42 So instead of pizzaView.toppings, 2:47 let's go with viewModel.switchStates. 2:52 That should do it for problem number one. 2:57 Let's run the app and see if it worked. 2:59 Let's create a new pizza. 3:12 Add a couple of toppings. 3:15 Give it a fun name. 3:20 And then rotate the app. 3:26 Awesome, it looks like everything worked. 3:29 Coming up in the next stage, we'll start diving into room, and 3:32 learn how we can store pizza in a database. 3:35
You need to sign up for Treehouse in order to download course files.Sign up