I'm using singleton object to hold data for the app which are changed or used on multiple places.
In my case, I have Arraylist of objects inside singleton. What I want to do is to iterate over this Arraylist and find one item with specific ID, then I want to copy this item and modify it. But what will happen is that If I copy this item from Singleton Arraylist and I will modify this coppied item, it will also modify that original item inside Singleton Arraylist.
Is there any way how to copy singleton item without acting like pointer?
Here is example code:
val foodList: ArrayList<Food> = AndroidSingleton.getInstance(this).foodList
val foodEntity: Food = foodList[1]
//foodList[1].foodID == 10
foodEntity.foodID = 7
//After step above foodList[1].foodID == 7 --> But I want to change only foodEntity ID
//use of coppied food Entity elsewhere
return foodEntity
Singleton:
class AndroidSingleton private constructor(private val context: Context?){
companion object : SingletonHolder<AndroidSingleton, Context>(::AndroidSingleton)
var foodList: ArrayList<Food> = ArrayList()
}
open class SingletonHolder<out T, in A>(creator: (A) -> T) {
private var creator: ((A) -> T)? = creator
@Volatile private var instance: T? = null
fun getInstance(arg: A): T {
val i = instance
if (i != null) {
return i
}
return synchronized(this) {
val i2 = instance
if (i2 != null) {
i2
} else {
val created = creator!!(arg)
instance = created
creator = null
created
}
}
}
}