platform-common-utilities/packages/pub_sub/example/main.dart

47 lines
1.6 KiB
Dart
Raw Normal View History

2021-09-11 13:46:31 +00:00
import 'dart:io';
import 'dart:isolate';
2023-12-12 01:30:25 +00:00
import 'package:belatuk_pub_sub/isolate.dart';
import 'package:belatuk_pub_sub/belatuk_pub_sub.dart';
2021-09-11 13:46:31 +00:00
void main() async {
// Easily bring up a server.
2023-12-12 01:30:25 +00:00
var adapter = IsolateAdapter();
var server = Server([adapter]);
2021-09-11 13:46:31 +00:00
// You then need to create a client that will connect to the adapter.
// Every untrusted client in your application should be pre-registered.
//
// In the case of Isolates, however, those are always implicitly trusted.
2023-12-12 01:30:25 +00:00
print("Register Client");
2021-09-11 13:46:31 +00:00
for (var i = 0; i < Platform.numberOfProcessors - 1; i++) {
2023-12-12 01:30:25 +00:00
server.registerClient(ClientInfo('client$i'));
2021-09-11 13:46:31 +00:00
}
// Start the server.
server.start();
// Next, let's start isolates that interact with the server.
//
// Fortunately, we can send SendPorts over Isolates, so this is no hassle.
2023-12-12 01:30:25 +00:00
print("Create Isolate");
2021-09-11 13:46:31 +00:00
for (var i = 0; i < Platform.numberOfProcessors - 1; i++) {
await Isolate.spawn(isolateMain, [i, adapter.receivePort.sendPort]);
}
// It's possible that you're running your application in the server isolate as well:
isolateMain([0, adapter.receivePort.sendPort]);
}
void isolateMain(List args) {
// Isolates are always trusted, so technically we don't need to pass a client iD.
2023-12-12 01:30:25 +00:00
var client = IsolateClient('client${args[0]}', args[1] as SendPort);
2021-09-11 13:46:31 +00:00
// The client will connect automatically. In the meantime, we can start subscribing to events.
client.subscribe('user::logged_in').then((sub) {
// The `ClientSubscription` class extends `Stream`. Hooray for asynchrony!
sub.listen((msg) {
print('Logged in: $msg');
});
});
}