|
| 1 | +import '../../../meta/hooks/hooks_meta.dart'; |
| 2 | + |
| 3 | +part 'channel_state.dart'; |
| 4 | + |
| 5 | +class ChannelCubit extends Cubit<ChannelState> { |
| 6 | + final ChannelRepository _channelRepo; |
| 7 | + ChannelCubit(this._channelRepo) : super(ChannelInitialState()); |
| 8 | + |
| 9 | + void resetFields() => emit(ChannelInitialState()); |
| 10 | + |
| 11 | + Future<void> loadChannel(String url) async { |
| 12 | + if (url.isEmpty) { |
| 13 | + emit(ChannelErrorState()); |
| 14 | + return; |
| 15 | + } |
| 16 | + emit(ChannelLoadingState()); |
| 17 | + try { |
| 18 | + final List<Object?> results = await Future.wait<Object?>([ |
| 19 | + _channelRepo.getChannelInfo(url), |
| 20 | + _channelRepo.getChannelUploads(url), |
| 21 | + ]); |
| 22 | + final YoutubeChannel? info = results[0] as YoutubeChannel?; |
| 23 | + final List<StreamInfoItem>? uploads = |
| 24 | + results[1] as List<StreamInfoItem>?; |
| 25 | + if (info != null) { |
| 26 | + return emit(ChannelLoadedState( |
| 27 | + channel: info, |
| 28 | + uploads: uploads ?? [], |
| 29 | + )); |
| 30 | + } |
| 31 | + return emit(ChannelErrorState()); |
| 32 | + } catch (e) { |
| 33 | + e.toString().print("ChannelCubit loadChannel Error"); |
| 34 | + return emit(ChannelErrorState()); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + Future<void> loadNextPage() async { |
| 39 | + final ChannelState currentState = state; |
| 40 | + if (currentState is! ChannelLoadedState || |
| 41 | + currentState.isLoadingMore || |
| 42 | + !currentState.hasMorePages) { |
| 43 | + return; |
| 44 | + } |
| 45 | + emit(currentState.copyWith(isLoadingMore: true)); |
| 46 | + try { |
| 47 | + final List<StreamInfoItem>? nextPage = |
| 48 | + await _channelRepo.getChannelNextPage(); |
| 49 | + if (nextPage != null && nextPage.isNotEmpty) { |
| 50 | + return emit(currentState.copyWith( |
| 51 | + uploads: <StreamInfoItem>[...currentState.uploads, ...nextPage], |
| 52 | + isLoadingMore: false, |
| 53 | + )); |
| 54 | + } |
| 55 | + return emit(currentState.copyWith( |
| 56 | + isLoadingMore: false, |
| 57 | + hasMorePages: false, |
| 58 | + )); |
| 59 | + } catch (e) { |
| 60 | + e.toString().print("ChannelCubit loadNextPage Error"); |
| 61 | + return emit(currentState.copyWith( |
| 62 | + isLoadingMore: false, |
| 63 | + hasMorePages: false, |
| 64 | + )); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments