Should I share my ViewModel across two fragments?
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?


add a comment |
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?


It does look like the official documentation recommends sharing the ViewModel: developer.android.com/topic/libraries/architecture/…
– Randy
Dec 31 '18 at 23:13
add a comment |
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?


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?




asked Dec 31 '18 at 21:43
RandyRandy
630514
630514
It does look like the official documentation recommends sharing the ViewModel: developer.android.com/topic/libraries/architecture/…
– Randy
Dec 31 '18 at 23:13
add a comment |
It does look like the official documentation recommends sharing the ViewModel: developer.android.com/topic/libraries/architecture/…
– Randy
Dec 31 '18 at 23:13
It does look like the official documentation recommends sharing the ViewModel: developer.android.com/topic/libraries/architecture/…
– Randy
Dec 31 '18 at 23:13
It does look like the official documentation recommends sharing the ViewModel: developer.android.com/topic/libraries/architecture/…
– Randy
Dec 31 '18 at 23:13
add a comment |
1 Answer
1
active
oldest
votes
The Android documentation suggested sharing a ViewModel for "a common case of master-detail fragments" so I decided to do the same for my case.
As suggested, I scoped the ViewModel to the Activity in both fragments:
entryViewModel = activity?.run {
ViewModelProviders.of(this, EntryViewModelFactory(this.application, EntryRepository(this.application))).get(EntryViewModel::class.java)
} ?: throw Exception("Invalid Activity")
Here's the commit where I made the change:
https://github.com/randroid88/TodayILearned/commit/e307bd3f238e68a399a2a1619438770d908a606d
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53991644%2fshould-i-share-my-viewmodel-across-two-fragments%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The Android documentation suggested sharing a ViewModel for "a common case of master-detail fragments" so I decided to do the same for my case.
As suggested, I scoped the ViewModel to the Activity in both fragments:
entryViewModel = activity?.run {
ViewModelProviders.of(this, EntryViewModelFactory(this.application, EntryRepository(this.application))).get(EntryViewModel::class.java)
} ?: throw Exception("Invalid Activity")
Here's the commit where I made the change:
https://github.com/randroid88/TodayILearned/commit/e307bd3f238e68a399a2a1619438770d908a606d
add a comment |
The Android documentation suggested sharing a ViewModel for "a common case of master-detail fragments" so I decided to do the same for my case.
As suggested, I scoped the ViewModel to the Activity in both fragments:
entryViewModel = activity?.run {
ViewModelProviders.of(this, EntryViewModelFactory(this.application, EntryRepository(this.application))).get(EntryViewModel::class.java)
} ?: throw Exception("Invalid Activity")
Here's the commit where I made the change:
https://github.com/randroid88/TodayILearned/commit/e307bd3f238e68a399a2a1619438770d908a606d
add a comment |
The Android documentation suggested sharing a ViewModel for "a common case of master-detail fragments" so I decided to do the same for my case.
As suggested, I scoped the ViewModel to the Activity in both fragments:
entryViewModel = activity?.run {
ViewModelProviders.of(this, EntryViewModelFactory(this.application, EntryRepository(this.application))).get(EntryViewModel::class.java)
} ?: throw Exception("Invalid Activity")
Here's the commit where I made the change:
https://github.com/randroid88/TodayILearned/commit/e307bd3f238e68a399a2a1619438770d908a606d
The Android documentation suggested sharing a ViewModel for "a common case of master-detail fragments" so I decided to do the same for my case.
As suggested, I scoped the ViewModel to the Activity in both fragments:
entryViewModel = activity?.run {
ViewModelProviders.of(this, EntryViewModelFactory(this.application, EntryRepository(this.application))).get(EntryViewModel::class.java)
} ?: throw Exception("Invalid Activity")
Here's the commit where I made the change:
https://github.com/randroid88/TodayILearned/commit/e307bd3f238e68a399a2a1619438770d908a606d
answered Jan 1 at 4:47
RandyRandy
630514
630514
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53991644%2fshould-i-share-my-viewmodel-across-two-fragments%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
It does look like the official documentation recommends sharing the ViewModel: developer.android.com/topic/libraries/architecture/…
– Randy
Dec 31 '18 at 23:13