Different fragment in a ViewPager with the same ViewModel.
See original GitHub issueI have a view model VMMain
class VMMain: ViewModel() {
private var pendingList = MutableLiveData<List<String>>()
var filteredPendingList: LiveData<List<String>> = Transformations.map(pendingList, { it })
var list = listOf("Hello", "Where", "Are", "You", "From", "It's", "Lonely", "Here")
fun filterList(searchString: String = "") {
if (searchString.isEmpty()) {
pendingList.value = list
} else {
pendingList.value = list.filter { it.contains(searchString, true) }
}
}
}
Then, I have a ViewPager with 2 fragments (fragment A & fragment B), each fragment use the above ViewModel VMMain & is initiated using
val vmMain by viewModel<VMMain>()
Using Koin, when I call vmMain.filterList("e")
in fragment A, the vmMain in fragment B also got triggered. I believe this is a bug. Because the behaviour should be the triggered view model should only be in fragment A. When I initiate the viewModel using ViewModelProviders.of(this).get(VMMain::class.java)
, it works fine.
I created a simple project to prove my point : https://github.com/hidrodixtion/KoinViewModelReport
Issue Analytics
- State:
- Created 6 years ago
- Comments:6 (5 by maintainers)
Top Results From Across the Web
Sharing ViewModel for Fragments in ViewPager2 or create ...
The way how it is now implemented, i have an Activity and a Fragment that have reference to the same ViewModel. From the...
Read more >Shared ViewModel Across Fragments
You will learn how to use a shared ViewModel to share data between the fragments of the same activity and new concepts like...
Read more >ViewPager with FragmentPagerAdapter
While a ViewPager is often coupled with a Fragment for each page using the FragmentPagerAdapter , there are cases where the pages are...
Read more >Viewmodels with ViewPager2 : r/androiddev
The easiest way is to use the parent fragment as the ViewModelStoreOwner. If your pages are different, you could have their own VMs,...
Read more >ViewPager Using Fragments in Android with Example
ViewPager · Steps for implementing viewpager: · Difference between FragmentPagerAdapter and FragmentStatePagerAdapter: · Following is the structure ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Updated: https://insert-koin.io/docs/1.0/quick-reference/android/#sharing-viewmodel
If you dont whant to reuse the ViewModel in both fragments just inject them with “fromActivity = false”
@param fromActivity - reuse ViewModel from parent Activity or create new one
viewModel(fromActivity = false)