Created
October 6, 2018 19:49
-
-
Save vferreirati/866e5bee6fc646d536ef150ec706d811 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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