Я сделал тест, в котором я определил:
Widget buildBody() {
return Column(
children: <Widget>[
StreamBuilder<int>(
stream: userBloc.outState,
initialData: 0,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
print("Builder 1");
print("Snapshot 1: " + snapshot.data.toString());
return (IconButton(
icon: Icon(Icons.favorite, color: Colors.red),
onPressed: () {
print("onPressed 1");
userBloc.inEvents.add(1);
}));
},
),
StreamBuilder<int>(
stream: userBloc.outState,
initialData: 0,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
print("Builder 2");
print("Snapshot 2: " + snapshot.data.toString());
return (IconButton(
icon: Icon(Icons.favorite, color: Colors.red),
onPressed: () {
print("onPressed 2");
userBloc.inEvents.add(2);
}));
},
)
],
);
И поток:
_outState = _userSubject.switchMap<int>(
(integer) {
print("Input (sink): " + integer.toString());
return doSomething(integer);
},
);
Когда я запускаю этот код и нажимаю IconButton 1, это вывод:
I/flutter ( 3912): Builder 1
I/flutter ( 3912): Snapshot 1: 0
I/flutter ( 3912): Builder 2
I/flutter ( 3912): Snapshot 2: 0
I/flutter ( 3912): onPressed 1
I/flutter ( 3912): Input (sink): 1
I/flutter ( 3912): Input (sink): 1
I/flutter ( 3912): Builder 1
I/flutter ( 3912): Snapshot 1: 1
I/flutter ( 3912): Builder 2
I/flutter ( 3912): Snapshot 2: 1
Как видите, надпись «Вход (сток): 1» показана дважды.Таким образом, для любого входа в приемник код внутри субъекта выполняется n раз, в зависимости от количества StreamBuilders, подписанных на поток.
Это поведение нормально, или это ошибка?
Я знаю, что функция построителя должна вызываться дважды, потому что любое изменение в потоке передается всем подписчикам StreamBuilder, но код внутри темы тоже должен вызываться дважды?