Skip to content

Instantly share code, notes, and snippets.

@xvrh
Created March 25, 2021 08:44
Show Gist options
  • Save xvrh/48ca148bd443228ea50c8b6460eb93fd to your computer and use it in GitHub Desktop.
Save xvrh/48ca148bd443228ea50c8b6460eb93fd to your computer and use it in GitHub Desktop.
Shelf hot reload
import 'dart:io';
import 'dart:developer' as dev;
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf/shelf.dart' as shelf;
import 'package:vm_service/utils.dart';
import 'package:vm_service/vm_service.dart';
import 'package:vm_service/vm_service_io.dart';
import 'package:watcher/watcher.dart';
import 'package:stream_transform/stream_transform.dart';
main() async {
var httpServer = await io.serve(
(request) async => shelf.Response.ok('My shelf handler'),
InternetAddress.anyIPv4,
0);
var observatoryUri = (await dev.Service.getInfo()).serverUri;
if (observatoryUri != null) {
var serviceClient = await vmServiceConnectUri(
convertToWebSocketUrl(serviceProtocolUrl: observatoryUri).toString(),
log: StdoutLog());
var vm = await serviceClient.getVM();
var mainIsolate = vm.isolates.first;
Watcher(Directory.current.path)
.events
.throttle(const Duration(milliseconds: 1000))
.listen((_) async {
await serviceClient.reloadSources(mainIsolate.id);
// TODO: invalidate cache etc...
print('App restarted ${DateTime.now()}');
});
} else {
print(
'You need to pass `--enable-vm-service --disable-service-auth-codes` to enable hot reload');
}
}
class StdoutLog extends Log {
void warning(String message) => print(message);
void severe(String message) => print(message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment