init
This commit is contained in:
50
lib/app/features/peers/controller/peers_controller.dart
Normal file
50
lib/app/features/peers/controller/peers_controller.dart
Normal file
@@ -0,0 +1,50 @@
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../../../backend/api/commands.dart' as commands;
|
||||
import '../../../../backend/discovery/model.dart';
|
||||
|
||||
part 'peers_controller.g.dart';
|
||||
|
||||
@riverpod
|
||||
class PeersController extends _$PeersController {
|
||||
@override
|
||||
Future<List<Peer>> build() async {
|
||||
return commands.getPeers();
|
||||
}
|
||||
|
||||
Future<void> refresh() async {
|
||||
state = const AsyncLoading();
|
||||
state = await AsyncValue.guard(commands.getPeers);
|
||||
}
|
||||
|
||||
void upsertPeer(Peer peer) {
|
||||
final current = state.asData?.value ?? const <Peer>[];
|
||||
final index = current.indexWhere((item) => item.id == peer.id);
|
||||
|
||||
if (index < 0) {
|
||||
state = AsyncData([...current, peer]);
|
||||
return;
|
||||
}
|
||||
|
||||
final old = current[index];
|
||||
if (old == peer) {
|
||||
return;
|
||||
}
|
||||
|
||||
final next = [...current];
|
||||
next[index] = peer;
|
||||
state = AsyncData(next);
|
||||
}
|
||||
|
||||
void removePeer(String id) {
|
||||
final current = state.asData?.value;
|
||||
if (current == null || current.isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
final next = current.where((item) => item.id != id).toList(growable: false);
|
||||
if (next.length != current.length) {
|
||||
state = AsyncData(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user