Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Forked from xvrh/hot_reload.dart
Created November 13, 2021 13:02
Show Gist options
  • Save PlugFox/2d8554f73720e6acea2a446d807fb9f5 to your computer and use it in GitHub Desktop.
Save PlugFox/2d8554f73720e6acea2a446d807fb9f5 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