Flutter,BLoC 需要 rx dart 吗?

Flutter, is rx dart required for BLoC?

在我看到的bloclibrary官网文档中,没看到他们用过rx dart。

然而,有时在社区中,他们说一起使用 rx dart 会更好。但我不明白。我正在使用 firestore 作为后端,我只是觉得我根本不需要 rxdart。即使我努力搜索,我也没能看到使用 rx dart + BLoC 的好的示例项目。

如果你在 BLoC 上使用 rx dart 有什么好处?我可以看一个例子吗?

您混淆了 BLoC 模式和 Bloc 库。

BLoC 模式是一种反应式状态管理解决方案,由 Google 创建。它的目标是充当应用程序中数据之间的中间人,例如,处理 API 和 UI 之间的状态和业务逻辑。

它是独立于平台的,这意味着 Bloc 中的相同 dart 代码将在 Flutter 和 Angular 等框架中工作。

通常,使用 RxDart,您可以像这样创建一个 BLoC:

class AppDataBloc {
  // The publish subject is responsible for get/add data and 
  // pass it to the UI as a stream.
  final _appDataSubject = PublishSubject<AppData>();

  // This is the stream the UI will use.
  Observable<AppData> get appData => _appDataSubject.stream;

}

另一方面,Bloc 库是 BLoC 模式的实现。

它不仅提供了一种简单、统一和直观的方式来实现 BLoC 模式,而且还使您的应用程序非常易于测试和维护。

所以要回答你的问题,你不需要 RxDart,除非你想自己实现 BLoC 模式。如果您使用 Bloc 库,那么您已经在使用 BloC 模式的 RxDart 免费实现。

如果你参考bloc package created by Felix Angelov you don't necessarily need to use rx_dart,但你可以。

例如,您可以在 transformEvents and/or 变换转换。通过这种方式,您可以操纵即将到来的事件(例如施加背压,这将避免服务器因太多请求而过载)

Bloc lifecycle

如果您想充分利用反应流,您可以探索 rx_bloc 生态系统,它是包含 [= 的业务逻辑组件模式的实现37=].

基本上你需要声明一个特定功能的契约,然后实现以反应方式符合它的集团。例如,如果您需要从 API 中获取一些新闻,您需要以这种方式声明合约:

/// A contract, containing all News BloC incoming events
abstract class NewsBlocEvents {
  /// Send a search event to the bloc with some payload
  void search({required String query});
}

/// A contract, containing all News BloC states
abstract class NewsBlocStates {
  /// The news found by the search query
  ///
  /// It can be controlled by executing [NewsBlocStates.search]
  ///
  Stream<Result<List<News>>> get news;
}

现在当所有合约都定义好后,你需要实现 Reactive BloC

/// A BloC responsible for the news
@RxBloc()
class NewsBloc extends $NewsBloc {
  /// The default constructor injecting a repository through DI
  NewsBloc(this._repository);
  
  /// The repository used for data source communication
  final NewsRepository _repository;

  /// Your events-to-sate business logic
  @override
  Stream<Result<List<News>>> _mapToNewsState() =>                 
      _$searchEvent
          /// Here you can apply any of the rx_dart operators
          /// for instance, you can apply back pressure
          .debounceTime(Duration(seconds: 1))
          /// Then you get the data from the repository
          .switchMap((_) => 
              _repository.decrement().asResultStream(),
          );
}

实现业务逻辑后,您可以使用 flutter_rx_bloc. There are plenty of articles 和示例访问小部件树中的 bloc,您可以在其中学习如何使用此生态系统。