0

I ran into a problem which I don't really understand. Maybe it is trivial, maybe I am just too tired and therefore I can't understand how it works at the moment.

I have a Firestore query which returns a list of object. In the onResult I try to store this result in a local variable so I can change its values later. My problem is that when I update this local variable somehow the original result changes too. I don't really understand how it is possible.

getParts(
            carId = carId,
            onResult = { vehicleParts ->
                //store callback result in local variable
                var updatedVehicleParts: List<VehiclePart> = mutableListOf()

                if (vehicleParts != null) {
                    updatedVehicleParts = vehicleParts
                }

                //update local variable -> (newValues is a parameter of the function)
                newValues.map { newPart ->
                    updatedVehicleParts.find { it.name == newPart.name }?.let {
                        it.currentHealth = newPart.maxLifeSpan
                        it.replacementTime = newPart.replacementTime
                    }
                }

                //here not only the local variable is updated BUT also the result of the callback
            },
            onError = {

            }
        )

I feel so stupid not recognizing something here...

d_vain
  • 25
  • 4
  • I added an answer before but completely misread what you're doing, sorry! What's the problem you're seeing here exactly? Which "local variable" are you talking about being updated, `updatedVehicleParts`? You're updating that as a *side-effect* of your `newValues.map` call, which produces a `List` (the result of your null-checked `let` expression which doesn't return a value). And because that's the last expression in your callback, that list is what the callback returns. Is that what you're talking about? If you let us know what exactly you want to return, we can tell you how to fix it – cactustictacs Nov 07 '22 at 00:23
  • There is no way you can do that. You cannot simply assign the value to a global variable and use it that way. Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a callback. You might also be interested in reading this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-cloud-firestore-using-get-bf03b6ee4953). – Alex Mamo Nov 07 '22 at 08:40

0 Answers0