【发布时间】:2021-01-06 14:51:46
【问题描述】:
我对 rxdart 如何与 bloc 模式一起工作有点困惑。这是我从 youtube 频道复制的代码。它是一个具有返回 API 响应的方法的块。在集团的某处通常有一个 mapEventToState 方法,但这个没有。我添加了一些 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 ?
【问题讨论】: