I have an async function which is called multiple times synchoronusly.
List response = await Future.wait([future, future])
Inside, it popups a form and waiting for it to be submitted or cancelled.
var val = await Navigator.push(
context,
MaterialPageRoute(builder : (context) => const TheForm())
);
The first served Future
will popup the form first and waiting for the return. No problem with that. But I want the second Future
to check first if the form is already popped up. If it is, it just waiting for it to conclude and receive the same returned value.
I’m aware that receiving same function return from two calls sounds crazy and impossible. I’m just looking for a way to hold the second Future
call on and trigger to conclude it from somewhere else.
Kindly tell me what I was missing and I’ll provide the required information.
2
Answers
I try to use
ValueNotifier
's. UnfortunatelyValueNotifier.addListener()
only accept aVoidCallback
. As for now, this is my solution. Still looking for a better way to replace the loop.It sounds like you want to coalesce multiple calls to an asynchronous operation. Make your asynchronous operation cache the
Future
it returns, and make subsequent calls return thatFuture
directly. For example:Now, no matter how many times you do
await foo();
,doActualWork()
will be executed at most once. (As pskink noted in a comment,AsyncMemoizer
frompackage:async
can do this for you.)If you instead want to allow
doActualWork()
to be executed multiple times and just to coalesce concurrent calls, then makedoActualWork
set_pending = null;
immediately before itreturn
s.