Should I share my ViewModel across two fragments?












0















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?










share|improve this question























  • It does look like the official documentation recommends sharing the ViewModel: developer.android.com/topic/libraries/architecture/…

    – Randy
    Dec 31 '18 at 23:13
















0















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?










share|improve this question























  • It does look like the official documentation recommends sharing the ViewModel: developer.android.com/topic/libraries/architecture/…

    – Randy
    Dec 31 '18 at 23:13














0












0








0








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?










share|improve this question














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?







android-fragments android-architecture-components android-architecture-livedata android-mvvm android-architecture-lifecycle






share|improve this question













share|improve this question











share|improve this question




share|improve this question










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



















  • 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












1 Answer
1






active

oldest

votes


















1














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






share|improve this answer























    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
    });


    }
    });














    draft saved

    draft discarded


















    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









    1














    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






    share|improve this answer




























      1














      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






      share|improve this answer


























        1












        1








        1







        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






        share|improve this answer













        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







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 1 at 4:47









        RandyRandy

        630514




        630514
































            draft saved

            draft discarded




















































            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.




            draft saved


            draft discarded














            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





















































            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







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

            Npm cannot find a required file even through it is in the searched directory