StreamBuilder triggers a method twice while the same operation as a variable triggered only once

Issue

I have a StreamBuilder that accepts a stream from my service. It looks like this:

StreamBuilder(
  stream: MyService.getStream$()
  builder (...)
);

Plus, I have my service with the following method:

getStream$() {
  print('being printed twice');
  return Observable.just('text')
    .doOnData(() => print('being printed twice too'));
}

When I run the app, I get the following prints being printed twice (each).

But, when I change the following implementation as a variable, it runs just once:

Observable getStream = Observable
  .just('text')
  .doOnData((data) => print('being printed once');

Of course, in the example above, I would use variables, but in my original code, I’m unable to do so because I’m depended on the instance properties.

What I can do, is to declare an Observable variable and in the constructor to set it to my desired observable. Although, this solution sounds like a workaround, and I’m not sure why would the the method would be triggered twice.

Any ideas?

Solution

StreamBuilder is rebuild every time build method is invoked. It means that MyService.getStream$() is evaluated with each invocation and creates new Observable. If you assign Observable to variable it will be created once and reused between build calls.

Take a look at this question Future running twice because it's in build method, how to fix it?
it’s about future but the mechanism is same.

Answered By – Filip P.

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *