flutterriverpod

Can Asynchronous Riverpod Notifier Methods get into a race with each other?


Let's say you have implemented a riverpod notifier class which holds a list of instances of a class in its state. That notifier class then also has a variety of different notifier methods which update the state by removing / adding list elements in multiple different ways. Some of them are asynchronous.

Let's say that your app then calls these notifier methods in a variety of different contexts / widgets, depending on whatever task executed in your app. That makes it possible that one of these asynchronous notifier methods may be called while another one is still running.

What I'm afraid of is that if two methods are called at nearly the same time (e.g., from different contexts in the app), and these methods both read from the state and then modify it: Could they overwrite each other's changes?

Or does riverpod implement some kind of FIFO-logic for this, to assure that notifier methods of the same notifier are always executed one after the other?

If riverpod does not assure this, I'd have to implement some kind of logic which "queues" all notifier calls via a (thus only) public method of the notifier, and then performs these state updates one-by-one internally by using a Queue and respective private notifier methods, both of these scoped to an internal use of the notifier only. To assure that there won't be any of the above-mentioned race-conditions.

But I wondered if that is not already provided anyways, by the package?


Solution

  • I guess you’re talking about handling concurrency in Riverpod. Unlike Flutter BLoC, which is event-based and processes events one at a time, Riverpod doesn’t handle concurrency for you.

    If you call two async notifier methods at the same time, there’s a chance they could overwrite each other’s changes, which is something to watch out for.

    To deal with this in Riverpod, you’d need to handle it manually using something like a Mutex or a custom queue to ensure updates happen one at a time.

    There was actually an issue raised in the Riverpod GitHub where it was clarified that concurrency needs to be managed manually,