如何解决使用RxDart使用Bloc模式处理API响应
我对rxdart与bloc模式如何工作有点困惑。这是我从YouTube频道复制的代码。它的集团拥有一种返回API响应的方法。通常在集团某个位置有一个 mapEventToState 方法,但实际上没有。我添加了一些评论以显示我的理解,并希望你们能纠正我。谢谢。
源代码: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 ?
解决方法
BLoC模式的重点是将业务逻辑与视图分开,以保持代码的清洁,可读和可测试。 mapEventToState
负责将事件转换为状态,您可以使用任何其他替代方法来实现。在Cubit
包中的bloc
中,我们定义了发出和更改状态的函数。
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}
在您提供的示例中,它定义了一个将改变状态的函数。因此,据我所知这是正确的,它被视为业务逻辑组件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。