Skip to content

Dependency Injection without external packages #249

Answered by rodydavis
anthonyaquino83 asked this question in Q&A
Discussion options

You must be logged in to vote

For never subscribing and never mutating you could create a signal like this:

final ReadonlySignal<Database> db = (){
  final Database connection = ...;
  final instance = signal(connection, autoDispose: true);
  instance.onDispose(() => connection.close());
  return instance;
}();

Or simpler approach that just makes a value readonly and a singleton:

final ReadonlySignal<SharedPreferences> prefs = signal(...);

void main() async {
  // Explicitly cast to set value
  (prefs as Signal<SharedPreferences>).value = await SharedPreferences.getInstance();
  ...
}

For both of these, .value will cause a 1 time subscription, but what you want is .peek() which will just return the value without subs…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@anthonyaquino83
Comment options

Comment options

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