Skip to content

Instantly share code, notes, and snippets.

@vferreirati
Created October 6, 2018 19:49
Show Gist options
  • Save vferreirati/866e5bee6fc646d536ef150ec706d811 to your computer and use it in GitHub Desktop.
Save vferreirati/866e5bee6fc646d536ef150ec706d811 to your computer and use it in GitHub Desktop.
// Other stuff ...
private lateinit var viewModelFactory: ViewModelFactory
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initViews()
viewModelFactory = ViewModelFactory(NotesRepository(this))
listViewModel = ViewModelProviders.of(this, viewModelFactory).get(NotesListViewModel::class.java)
listViewModel.allNotes.observe(this, Observer {
noteAdapter.updateNotes(it)
})
}
// Other stuff ...
class ViewModelFactory(private val notesRepository: NotesRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T =
when {
modelClass.isAssignableFrom(NotesListViewModel::class.java) ->
NotesListViewModel(notesRepository) as T
modelClass.isAssignableFrom(EditorViewModel::class.java) ->
EditorViewModel(notesRepository) as T
else -> throw IllegalArgumentException("ViewModel not found")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment