【问题标题】:Handling api response with bloc pattern with rxdart使用 rxdart 处理具有 bloc 模式的 api 响应
【发布时间】:2021-01-06 14:51:46
【问题描述】:

我对 rxdart 如何与 bloc 模式一起工作有点困惑。这是我从 youtube 频道复制的代码。它是一个具有返回 API 响应的方法的块。在集团的某处通常有一个 ma​​pEventToState 方法,但这个没有。我添加了一些 cmets 来展示我的理解,希望你们能纠正我。谢谢。

源码:https://github.com/bilguunint/igdb/blob/master/lib/bloc/get_games_bloc.dart

class GetGamesBloc {

    final GameRepository _repository = GameRepository(); // defining the api repository

    final BehaviorSubject<GameResponse> _subject = BehaviorSubject<GameResponse>();
    // defining a behaviour stream which will give only the latest item/data 

    getGames(int platformId) async {
      GameResponse response = await _repository.getGames2(platformId);
      _subject.sink.add(response);
    }
    // this method fetches the api data but not sure why add response to the sink. Isnt sink suppose to be an event? The response is an api json data so it's a stream right ? 

   dispose() {
      _subject.close();
    }
   //closing the stream when not in use to prevent memory loss

    BehaviorSubject<GameResponse> get subject => _subject;
   // defining a getter to be used outside the class

}
final getGamesBloc = GetGamesBloc();
// I think this enables us to use the bloc as getGamesBloc ? 

【问题讨论】:

    标签: flutter bloc rxdart


    【解决方案1】:

    BLoC 模式的重点是将业务逻辑与视图分离,以保持代码的清洁、可读性和可测试性。 mapEventToState 负责将事件转换为状态,您可以使用任何其他替代方法来做到这一点。在来自bloc 包的Cubit 中,我们定义了发出和更改状态的函数。

    class CounterCubit extends Cubit<int> {
      CounterCubit() : super(0);
    
      void increment() => emit(state + 1);
      void decrement() => emit(state - 1);
    }
    

    在您提供的示例中,它定义了一个将改变状态的函数。所以,据我所知,这是正确的,它算作业务逻辑组件。

    【讨论】:

    猜你喜欢
    • 2019-07-19
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 2019-03-31
    • 2020-01-26
    • 2023-02-20
    • 1970-01-01
    • 2016-07-13
    相关资源
    最近更新 更多