44 lines
1.2 KiB
Dart
44 lines
1.2 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:developer';
|
|
|
|
import 'package:flutter/cupertino.dart';
|
|
import 'package:marianum_mobile/dataOld/socketConnection.dart';
|
|
|
|
class IncomingPacket extends ChangeNotifier {
|
|
|
|
String packetId;
|
|
bool useJsonDecode;
|
|
|
|
bool _isReceived = false;
|
|
bool get isReceived => _isReceived;
|
|
|
|
IncomingPacket(this.packetId, {this.useJsonDecode = true}) {
|
|
SocketConnection.read.listen((event) {
|
|
if(event.startsWith("$packetId:")) {
|
|
_isReceived = true;
|
|
|
|
// THIS listener handles the incomming request
|
|
log("$packetId is handled!");
|
|
String content = event.split("$packetId:")[1];
|
|
handle(useJsonDecode ? jsonDecode(content) : content);
|
|
}
|
|
notifyListeners();
|
|
});
|
|
}
|
|
|
|
void invoke({Object? data, bool indicateLoading = false, bool allowNotifyListeners = true}) {
|
|
data = data ?? {};
|
|
log("$packetId is invoked with data: $data");
|
|
SocketConnection.write.add("$packetId:${jsonEncode(data)}");
|
|
|
|
if(indicateLoading) {
|
|
_isReceived = false;
|
|
if(allowNotifyListeners) notifyListeners();
|
|
}
|
|
}
|
|
|
|
void handle(dynamic data) {
|
|
log("Warning: $packetId packet listener is registered, but no handle is defined!");
|
|
}
|
|
} |