mchess-client/lib/connection_cubit/connection_cubit.dart

79 lines
2.0 KiB
Dart
Raw Normal View History

import 'package:flutter_bloc/flutter_bloc.dart';
import '../connection/ws_connection.dart';
class ConnectionCubit extends Cubit<ConnectionCubitState> {
static final ConnectionCubit _instance = ConnectionCubit._internal();
ConnectionCubit._internal() : super(ConnectionCubitState.init());
factory ConnectionCubit.getInstance() {
return ConnectionCubit();
}
factory ConnectionCubit() {
return _instance;
}
void connect(String playerID, String? passphrase) {
2024-05-21 16:48:06 +00:00
var connectedFuture =
ServerConnection.getInstance().connect(playerID, passphrase);
connectedFuture?.then((val) {
emit(ConnectionCubitState(
iAmConnected: true,
connectedToPhrase: passphrase,
opponentConnected: false));
});
}
void connectIfNotConnected(String playerID, String? passphrase) {
if (state.iAmConnected && state.connectedToPhrase == passphrase) {
return;
}
if (state.iAmConnected && state.connectedToPhrase != passphrase) {
disonnect().then((val) {
connect(playerID, passphrase);
});
}
connect(playerID, passphrase);
}
Future disonnect() async {
2024-05-21 16:48:06 +00:00
var disconnectFuture =
ServerConnection.getInstance().disconnectExistingConnection();
disconnectFuture.then(
(val) {
emit(ConnectionCubitState.init());
},
);
return disconnectFuture;
2023-06-29 23:49:18 +00:00
}
void opponentConnected() {
2024-05-21 16:48:06 +00:00
emit(ConnectionCubitState(
iAmConnected: state.iAmConnected,
connectedToPhrase: state.connectedToPhrase,
opponentConnected: true));
}
}
class ConnectionCubitState {
2024-05-21 16:48:06 +00:00
final bool iAmConnected;
final String? connectedToPhrase;
2023-06-29 23:49:18 +00:00
final bool opponentConnected;
2024-05-21 16:48:06 +00:00
ConnectionCubitState(
{required this.iAmConnected,
required this.connectedToPhrase,
required this.opponentConnected});
factory ConnectionCubitState.init() {
2024-05-21 16:48:06 +00:00
return ConnectionCubitState(
iAmConnected: false, connectedToPhrase: null, opponentConnected: false);
}
}