StreamBuilder仅接收流中的最后一项

时间:2018-12-23 12:33:51

标签: flutter rxdart

我的ApplicationBloc是小部件树的根。在Bloc的构造函数中,我正在侦听来自包含从JSON解码的模型的存储库中的流,并将其转发到StreamBuilder侦听的另一个流。

我希望StreamBuilder会一一接收模型并将其添加到AnimatedList中。但这是一个问题:StreamBuilder的生成器仅对流中的最后一项触发一次。

例如,几个模型位于id为0、1、2和3的本地存储中。所有这些都是从存储库发出的,所有这些都已成功放入流控制器中,但只有最后一个模型(id为== 3)出现在AnimatedList中。

存储库:

class Repository {
  static Stream<Model> load() async* {
    //...
    for (var model in models) {
      yield Model.fromJson(model);
    }
  }
}

集团:

class ApplicationBloc {
  ReplaySubject<Model> _outModelsController = ReplaySubject<Model>();
  Stream<Model> get outModels => _outModelsController.stream;

  ApplicationBloc() {
    TimersRepository.load().listen((model) => _outModelsController.add(model));
  }
}

main.dart:

void main() {
  runApp(
    BlocProvider<ApplicationBloc>(
      bloc: ApplicationBloc(),
      child: MyApp(),
    ),
  );
}

//...

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    final ApplicationBloc appBloc = //...

    return MaterialApp(
      //...
      body: StreamBuilder(
        stream: appBloc.outModels,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            var model = snapshot.data;
            /* inserting model to the AnimatedList */
          }

          return AnimatedList(/* ... */);
        },
      ),
    );
  }
}

有趣的通知:在StreamBuilder的_subscribe()方法中,onData()回调触发所需的次数,但build()方法仅触发一次。

1 个答案:

答案 0 :(得分:1)

您需要一个Stream来输出List<Model而不是单个元素。另外,侦听流以将其添加到另一个ReplaySubject会将输出流延迟2(!!!)帧,因此最好有一个链。

class TimersRepository {
  // maybe use a Future if you only perform a single http request!
  static Stream<List<Model>> load() async* {
    //...
    yield models.map((json) => Model.fromJson(json)).toList();
  }
}

class ApplicationBloc {
  Stream<List<Model>> get outModels => _outModels;
  ValueConnectableObservable<List<Model>> _outModels;
  StreamSubscription _outModelsSubscription;

  ApplicationBloc() {
    // publishValue is similar to a BehaviorSubject, it always provides the latest value,
    // but without the extra delay of listening and adding to another subject
    _outModels = Observable(TimersRepository.load()).publishValue();

    // do no reload until the BLoC is disposed
    _outModelsSubscription = _outModels.connect();
  }

  void dispose() {
    // unsubcribe repo stream on dispose
    _outModelsSubscription.cancel();
  }
}

class _MyAppState extends State<MyApp> {
  ApplicationBloc _bloc;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<Model>>(
      stream: _bloc.outModels,
      builder: (context, snapshot) {
        final models = snapshot.data ?? <Model>[];
        return ListView.builder(
          itemCount: models.length,
          itemBuilder: (context, index) => Item(model: models[index]),
        );
      },
    );
  }
}