Home > OS >  How to share a viewmodel between 2 fragments that are tabs
How to share a viewmodel between 2 fragments that are tabs

Time:11-03

So I have 3 fragments, fragmentA , fragmentB and fragmentC

in fragmentA I create a viewpager with 2 tabs (fragmentB and fragmentC)

FragmentA

 private fun setupTabLayoutWithViewPager() {
        binding.viewPager.disableUserSwipeLeftRight()
       
        binding.viewPager.adapter = MyCustomStateAdapter(this, this)

        val tabLayout = binding.tabLayout

        TabLayoutMediator(tabLayout, binding.viewPager) { tab, position ->
            tab.text = when (position) {
                0 -> ResourceUtils.getString(R.string.firstTab)
                1 -> ResourceUtils.getString(R.string.secondTab)
                else -> emptyString()
            }
        }.attach()

        tabLayout.allowEachTabWithEqualWidth()
    }

now , from fragmentB and fragmentC that are created with this MyCustomStateAdapter I want to share the viewmodel between them, so in my fragmentA since its the parent of these two fragments I did this for the instance of the viewmodel

FragmentA

 private val viewModel: MyViewModel by viewModels(ownerProducer = { requireParentFragment() }) {
        createVMFactory {
            MyViewModel(
                MyRepo()
            )
        }
    }

Now, do I need to paste this same exact code in fragmentB and fragmentC to access the instance of the viewmodel created by fragmentA ? because I want to share this same viewmodel between these 3 fragments

Thanks

CodePudding user response:

So in fragmentA it should be

private val viewModel: MyViewModel by viewModels {
        createVMFactory {
            MyViewModel(
                MyRepo()
            )
        }
    }

and in the other fragments (the tab ones)

 private val viewModel: MyViewModel by viewModels(ownerProducer = { requireParentFragment() }) {
        createVMFactory {
            MyViewModel(
                MyRepo()
            )
        }
    }

since we create the first viewmodel with the ownerProducer as this (the parent fragment) and its childs will get the parent fragment and get the viewmodel instance stored on this owner

CodePudding user response:

You can share data between fragment in one activity with activityViewModel. Maybe this codelab will help you

  • Related