I have an application, and I am trying to retrieve a list of products from cloud firestore. The code:
private var foodPetitions2: MutableList<FoodPetition> = mutableListOf()
private var adapter = FoodAdapter2(foodPetitions2, this)
private var db = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_category_products)
val bundle = intent.extras
val docs = db.collection("productos").whereEqualTo("category", bundle?.get("category"))
docs.get().addOnSuccessListener {
for (document in it){
addItem(FoodPetition(document.data["name"] as String, document.data["image"] as String, document.data["id"] as String))
}
addItem(FoodPetition("s", "a", "asdas"))
}
foodPetitions2.forEach{
println(it.name)
println(it.image)
println(it.id)
}
setup()
}
The problem is that the changes to variables that I make inside the addOnSuccessListener are not saved, and I don't understand why.
Changes are saved, just not instantly. As the name of the function indicates,
OnSuccessListener
it is executed when the query completes successfully. In your code you're printing the list immediately after doing the query, so it's not going to print anything because there's no way for your query to complete before that point. If you need to use the result of the query, you must do it inside the callback or you can also use the await function to wait for the query to finish.