Skip to content

using ref.keepAlive() vs @Riverpod(keepAlive: true) #3584

Answered by rrousselGit
2kjm asked this question in Q&A
Discussion options

You must be logged in to vote

@Riverpod(keepAlive: true) can be used by the linter to know if a provider is always kept alive.
But ref.keepAlive() can't

In terms of how they impact your app, both work the same. But one of them empowers riverpod_lint to tell you when you're doing something wrong.

Also, be careful with ref.keepAlive() + async*

async* implies an await null at its start.

If you write:

@riverpod
Stream<Model> example(ref) async* {
  ref.keepAlive();
}

That's like if you did:

@riverpod
Future<Model> example(ref) async {
  await null;
  ref.keepAlive();
}

So there's a small chance your provider gets disposed before ref.keepAlive is reached.

Replies: 3 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@2kjm
Comment options

@dohyxx
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by rrousselGit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants