import 'dart:async'; import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:selfprivacy/config/get_it_config.dart'; import 'package:selfprivacy/logic/models/json/server_job.dart'; export 'package:provider/provider.dart'; part 'server_jobs_state.dart'; part 'server_jobs_event.dart'; class ServerJobsBloc extends Bloc { ServerJobsBloc() : super( ServerJobsInitialState(), ) { final apiConnectionRepository = getIt(); _apiDataSubscription = apiConnectionRepository.dataStream.listen( (final ApiData apiData) { add( ServerJobsListChanged([...apiData.serverJobs.data ?? []]), ); }, ); on( _mapServerJobsListChangedToState, ); on( _mapRemoveServerJobToState, ); on( _mapRemoveAllFinishedJobsToState, ); } StreamSubscription? _apiDataSubscription; Future _mapServerJobsListChangedToState( final ServerJobsListChanged event, final Emitter emit, ) async { if (event.serverJobList.isEmpty) { emit(ServerJobsListEmptyState()); return; } final newState = ServerJobsListWithJobsState(serverJobList: event.serverJobList); emit(newState); } Future _mapRemoveServerJobToState( final RemoveServerJob event, final Emitter emit, ) async { await getIt().removeServerJob(event.uid); } Future _mapRemoveAllFinishedJobsToState( final RemoveAllFinishedJobs event, final Emitter emit, ) async { final List finishedJobs = state.serverJobList .where( (final ServerJob job) => job.status == JobStatusEnum.finished || job.status == JobStatusEnum.error, ) .toList(); for (final ServerJob job in finishedJobs) { await getIt().removeServerJob(job.uid); } } @override void onChange(final Change change) { super.onChange(change); } @override Future close() { _apiDataSubscription?.cancel(); return super.close(); } }