Eliya Cohen
Eliya Cohen

Reputation: 11468

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

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?

Upvotes: 1

Views: 529

Answers (1)

Filip P.
Filip P.

Reputation: 1354

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.

Upvotes: 1

Related Questions