Riverpod comes with a lot of terms and options and latest Riverpod has introduced a new term called AutoDisposeNotifierProvider.
And what is this AutoDisposeNotifierProvider. In general if you mark your code as @riverpod when generating code of Riverpod using code generation tool, then you can AutoDisposeNotifierProvider.
And let’s see an example of a code snippet and then it will make more sense. The below code has been auto generated by code generation tool.
Here we created a Notifier class and you may see it clearly on line 12, it’s mentioned as ProviderFor(TodosNotifier)
Then what is our Provider, it’s todosNotifierProvider on line 13. This provider has been created and should be disposed or removed when not needed to free up the memory.
AutoDisposeNotifierProvider is subclass of AutoDisposeRef and let’s check it out from the package code itself.
You may also read the commenting AutoDisposeRef or Ref automatically get destroyed when not needed.
You may also forcefully destroy it.
Here below in the video, I gave a live example of AutoDisposeNotifierProvider. We have maintained the dots indicators state’s using NotifierProvider and again using AutoDisposeNotifierProvider so that you can see the difference. Watch the below video please.
Warning
Requests for the state of a provider will not be disposed when all the listeners of the provider are removed
From the video, you understand the Providers are disposed once they are not needed. This is the default behavior or Riverpod 2.0. But this could change if you.
To change this we need to change the annotation type. We could simply add @Riverpod(keepAlive:true) instead of @riverpod.
See on line 4, that we have used @Riverpod(keepAlive:true). That’s it.
Complete project using Riverpod 2.0