In Flutter, I have an async function that should not be called twice at the same time.
Here's a minimal example
class DatabaseHelper {
Future<void> add100elements() async {
// this functions queries a database and adds 100 elements from the db to a local list
var elementsToAdd = await db.rawQuery('select * from quotes where id > ? limit 100', this.currentId);
this.localList.addAll(elementsToAdd);
this.currentId += 100;
}
}
There could be two different places in the app that call add100elements
at almost the same twice. That means the code will be executed twice, and add the same 100 elements.
I want to avoid this, by preventing the add100elements
function to be called twice.
I could simply do this:
class DatabaseHelper {
bool isRunning = false;
Future<void> add100elements() async {
// this functions queries a database and adds 100 elements from the db to a local list
if (isRunning) return;
isRunning = true;
var elementsToAdd = await db.rawQuery('select * from quotes where id > ? limit 100', this.currentId);
this.localList.addAll(elementsToAdd);
this.currentId += 100;
isRunning = false;
}
}
But that feels a little manual and clumsy.
Is there a built-in way to do this in dart? Or a better way?