pikapika/lib/basic/Channels.dart

54 lines
1.3 KiB
Dart
Raw Permalink Normal View History

2021-09-29 23:57:09 +00:00
import 'dart:async';
import 'dart:convert';
import 'package:flutter/services.dart';
2021-10-21 04:08:51 +00:00
// EventChannel
// 由于Flutter的EventChannel只能订阅一次, 且为了和golang的的通信, 这里实现了多次订阅的分发和平铺
// 根据eventName订阅和取消订阅
2022-03-17 03:31:25 +00:00
var _eventChannel = const EventChannel("flatEvent");
2021-09-29 23:57:09 +00:00
StreamSubscription? _eventChannelListen;
Map<void Function(String args), String> _eventMap = {};
void registerEvent(void Function(String args) eventHandler, String eventName) {
if (_eventMap.containsKey(eventHandler)) {
throw 'once register';
}
_eventMap[eventHandler] = eventName;
if (_eventMap.length == 1) {
_eventChannelListen =
_eventChannel.receiveBroadcastStream().listen(_onFlatEvent);
}
}
void unregisterEvent(void Function(String args) eventHandler) {
if (!_eventMap.containsKey(eventHandler)) {
throw 'no register';
}
_eventMap.remove(eventHandler);
2022-03-17 03:31:25 +00:00
if (_eventMap.isEmpty) {
2021-09-29 23:57:09 +00:00
_eventChannelListen?.cancel();
}
}
void _onFlatEvent(dynamic t) {
_FlatEvent e = _FlatEvent.fromJson(jsonDecode(t));
_eventMap.forEach((key, value) {
if (value == e.function) {
key(e.content);
}
});
}
class _FlatEvent {
late String function;
late String content;
_FlatEvent.fromJson(Map<String, dynamic> json) {
this.function = json["function"];
this.content = json["content"];
}
}