import 'dart:async'; import 'package:bloc_concurrency/bloc_concurrency.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:selfprivacy/config/get_it_config.dart'; import 'package:selfprivacy/logic/api_maps/generic_result.dart'; import 'package:selfprivacy/logic/models/json/api_token.dart'; part 'devices_event.dart'; part 'devices_state.dart'; class DevicesBloc extends Bloc { DevicesBloc() : super(DevicesInitial()) { on( _mapDevicesListChangedToState, transformer: sequential(), ); on( _mapDeleteDeviceToState, transformer: sequential(), ); final apiConnectionRepository = getIt(); _apiDataSubscription = apiConnectionRepository.dataStream.listen( (final ApiData apiData) { add( DevicesListChanged(apiData.devices.data), ); }, ); } StreamSubscription? _apiDataSubscription; Future _mapDevicesListChangedToState( final DevicesListChanged event, final Emitter emit, ) async { if (state is DevicesDeleting) { return; } if (event.devices == null) { emit(DevicesError()); return; } emit(DevicesLoaded(devices: event.devices!)); } Future refresh() async { getIt().apiData.devices.invalidate(); await getIt().reload(null); } Future _mapDeleteDeviceToState( final DeleteDevice event, final Emitter emit, ) async { // Optimistically remove the device from the list emit( DevicesDeleting( devices: state.devices .where((final d) => d.name != event.device.name) .toList(), ), ); final GenericResult response = await getIt() .api .deleteApiToken(event.device.name); if (response.success) { getIt().apiData.devices.invalidate(); emit( DevicesLoaded( devices: state.devices .where((final d) => d.name != event.device.name) .toList(), ), ); } else { getIt() .showSnackBar(response.message ?? 'Error deleting device'); emit(DevicesLoaded(devices: state.devices)); } } Future getNewDeviceKey() async { final GenericResult response = await getIt().api.createDeviceToken(); if (response.success) { return response.data; } else { getIt().showSnackBar( response.message ?? 'Error getting new device key', ); return null; } } @override void onChange(final Change change) { super.onChange(change); } @override Future close() { _apiDataSubscription?.cancel(); return super.close(); } }