freezer/lib/api/download_manager/service_interface.dart

47 lines
1.1 KiB
Dart

import 'dart:collection';
import 'dart:isolate';
import 'package:flutter_background_service/flutter_background_service.dart';
typedef ListenerCallback = void Function(Map<String, dynamic>? args);
class ServiceInterface {
final ReceivePort? receivePort;
late SendPort sendPort;
final ServiceInstance? service;
bool _isListening = false;
final _listeners = HashMap<String, ListenerCallback>();
ServiceInterface({this.receivePort, this.service})
: assert(receivePort != null || service != null);
void on(String method, ListenerCallback listener) {
if (service != null) {
service!.on(method).listen(listener);
}
if (!_isListening) {
_isListening = true;
receivePort!.listen((message) {
final method = message['_'];
_listeners[method]!.call(message);
});
}
_listeners[method] = listener;
}
void no(String method) {
_listeners.remove(method);
}
void send(String method, [Map<String, dynamic>? args]) {
if (service != null) {
return service!.invoke(method, args);
}
sendPort!.send({'_': method, if (args != null) ...args});
}
}