Reputation: 279
I'm setting kotlin mutable map in my viewModel like this,
// In ViewModel
var mapData= mutableMapOf<Int, String>()
in my fragment i'm referring this map as below,
//In fragment
lateinit var _mapData: MutableMap<Int, String>
// in oncreate View
_mapData[1] = "one"
When i run above code, this _mapData
is automatically updated to my viewModel mapData
. I don't want that,
Where I'm having real problem is in the below code,
// initiallizing
if(!_mapData.contains(2)){
_mapData[2] = _mapData[1]
}
//doing some process to get the actual _mapData[2]
_mapData[2] = "Two"
After running the above code my _mapData[1]
is also changing to "Two"
.
What is this behaviour and why is it happening
Upvotes: 0
Views: 454
Reputation: 7788
Not sure how you assign _mapData
from mapData
, but if you simply write:
_mapData = viewModel.mapData
then both variables store reference to the same exact map object. Thus, if you change anything via mapData
reference, _mapData
content will also change (because it's the same object).
If you want to have separate entities of map in viewModel and fragment, you should copy the map:
_mapData = viewModel.mapData.toMutableMap()
Upvotes: 3