I'm attempting to follow Android best practices and use the latest recommended architecture components. You can see my attempt so far here: https://github.com/randroid88/TodayILearned
Right now the app's features are very limited.
- It has a Room db for locally storing journal entries.
- One fragment, HomeFragment, that lists all the entries
- Another fragment, EntryEditorFragment, that creates new entries.
- A ViewModel, EntryViewModel, that updates the data via a repository.
The problem is that only HomeFragment has access to EntryViewModel right now.
So in my current design, I pass the new entry text from EntryEditorFragment to HomeFragment via an argument bundle (using SafeArgs from the new Navigation Architecture Component), then HomeFragment creates the new entry via the EntryViewModel:
val safeArgs = HomeFragmentArgs.fromBundle(arguments!!)
savePossibleNewEntry(safeArgs.entryText)
private fun savePossibleNewEntry(entryText: String) {
entryViewModel!!.insert(EntryCreator().create(entryText))
}
This doesn't feel right.
Would it be better if EntryViewModel also had access to EntryEditorFragment?
In order to accomplish this, would I have to scope the ViewModel to the Activity as explained here on this blog?
What is the best practice here?