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
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
Updated: https://insert-koin.io/docs/1.0/quick-reference/android/#sharing-viewmodel
@arnaudgiuliani the link is not working :(
Yep sorry :/
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)