0

To my basic understanding of Stream and sink we add data to sink in order to pass it through the stream but to add it we use a getter instead of setter, which I find counter-intuitive (see example below), could you please explain in simple words why is it how it is and not the other way around?

Example:

class BlogPostViewModel {
  StreamController<List<BlogPost>> _blogPostListController = StreamController.broadcast();
  Stream<List<BlogPost>> get outBlogPostList => _blogPostListController.stream;
  Sink<List<BlogPost>> get _inBlogPostList => _blogPostListController.sink; // Here why use get and not a setter?
}

In advance, thank you.

julemand101
  • 28,470
  • 5
  • 52
  • 48

1 Answers1

0

The getter and setter concept is a way to simulate access to a field in a class but control the behavior of this. So behind the scene there can even not be any variable if we want to e.g. have a getter which fetch some data from somewhere each time (please don't do that).

get and set are therefore methods called when we try to get and set the value of this field:

class MyClass {
  void get test => print('You called get');
  set test(void input) => print('You called set');
}

void main() {
  final obj = MyClass();
  obj.test;         // You called get
  obj.test = null;  // You called set
}

So in your case, you want to make so when you try to get the "variable" named _inBlogPostList you will instead get the result of _blogPostListController.sink.

The advantage of this is you get a Sink instance which you can call add and close on. If you don't need to close the sink you can instead use a set method to add stuff into the sink like Rémi Rousselet proposes.

julemand101
  • 28,470
  • 5
  • 52
  • 48