I have certain products and I need them not to be purchased by several users at the same time as they could buy more than the available amount. For this, every time a user starts the process of buying a product, I change a property of my database ( isBeingBought/idDelProducto
) to true. So, if a user initiates a purchase, I want the app to confirm that no one else is buying the product ( isBeingBought/idDelProducto == false
) and if someone else is ( isBeingBought/idDelProducto == true
), I want the app to wait until the property returns to false
.
For this I made the function awaitNobodyIsBuying
that is a Future
that waits until the property istrue
static Future<void> awaitNobodyIsBuying(String id, String weight) async {
DatabaseReference ref = await FirebaseDatabase.instance.ref()
.child("isBeingBought/$id");
final body = await ref.get();
if(body.value!=null && body.value as bool){
await Future.delayed(Duration(seconds: 1)).then((event) {
awaitNobodyIsBuying(id, weight);
});
}
}
What this function does is ask if the property is true
and if it is, wait a second and ask again.
I call it when the buy button is pressed:
onPressed:() async {
await ProductDatabaseService.awaitNobodyIsBuying(buyProducProvider.productSelected!.id, buyProducProvider.caliberSelected!.weight);
//Realizar compra....
}
the problem is that the method works correctly, when checking it with the Debugger it keeps looping until I manually change the property to false
. However, the application does not wait and while the method awaitNobodyIsBuying
is still executing, the other methods are still executing.
I use firebase realtime database.
How can I solve that? Is there a more efficient method with a listener or something?
When you use it, it
await
stops the flow until you get a response, but when you usethen
, what you do is receive the response asynchronously while the flow continues, you would have to wait and return, like this: