Koin: Different fragment in a ViewPager with the same ViewModel.

Created on 13 Feb 2018  路  6Comments  路  Source: InsertKoinIO/koin

I 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

Most helpful comment

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)

All 6 comments

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)

Info is missing from the documentation. I will add it to Quick ref

@arnaudgiuliani the link is not working :(

Yep sorry :/

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sankarsana picture sankarsana  路  4Comments

guymclean picture guymclean  路  3Comments

AHarazim picture AHarazim  路  3Comments

dakuenjery picture dakuenjery  路  4Comments

erikhuizinga picture erikhuizinga  路  3Comments