Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ProjectEditorFragment showing how to use ViewModels to restore state.
class ProjectEditorFragment : Fragment {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var viewModel: ProjectEditorViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_editor_initial, container, false)
AndroidSupportInjection.inject(this)
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(requireActivity(), viewModelFactory)
.get(ProjectEditorViewModel::class.java)
setupViewModel()
}
private fun setupViewModel() {
viewModel.state.observe(this, Observer { editorState ->
editorState?.let { state ->
// Set the state of all controls based on the saved state in the ViewModel
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment