platform/packages/pub_sub/example/main.dart

45 lines
1.6 KiB
Dart
Raw Normal View History

2021-03-08 12:56:39 +00:00
import 'dart:io';
import 'dart:isolate';
2021-05-15 11:20:33 +00:00
import 'package:angel3_pub_sub/isolate.dart' as pub_sub;
import 'package:angel3_pub_sub/angel3_pub_sub.dart' as pub_sub;
2021-03-08 12:56:39 +00:00
2021-05-15 11:20:33 +00:00
void main() async {
2021-03-08 12:56:39 +00:00
// Easily bring up a server.
2021-05-15 11:20:33 +00:00
var adapter = pub_sub.IsolateAdapter();
var server = pub_sub.Server([adapter]);
2021-03-08 12:56:39 +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.
2021-05-18 13:55:30 +00:00
for (var i = 0; i < Platform.numberOfProcessors - 1; i++) {
2021-05-15 11:20:33 +00:00
server.registerClient(pub_sub.ClientInfo('client$i'));
2021-03-08 12:56:39 +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.
2021-05-15 11:20:33 +00:00
for (var i = 0; i < Platform.numberOfProcessors - 1; i++) {
2021-03-08 12:56:39 +00:00
await Isolate.spawn(isolateMain, [i, adapter.receivePort.sendPort]);
2021-05-15 11:20:33 +00:00
}
2021-03-08 12:56:39 +00:00
// 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.
2021-05-15 11:20:33 +00:00
var client = pub_sub.IsolateClient('client${args[0]}', args[1] as SendPort);
2021-03-08 12:56:39 +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');
});
});
}