diff --git a/samples/ffi/httpIG/lib/http.dart b/samples/ffi/httpIG/lib/http.dart index b150d47ea34..0a1024de352 100644 --- a/samples/ffi/httpIG/lib/http.dart +++ b/samples/ffi/httpIG/lib/http.dart @@ -12,6 +12,15 @@ import 'package:ffi/ffi.dart'; import 'dylib_utils.dart'; +Function (Pointer) createGetSender(SendPort sendPort) { + return (Pointer responsePointer) { + final typedList = responsePointer.cast().asTypedList( + responsePointer.length, + ); + sendPort.send(utf8.decode(typedList)); + }; +} + // Runs a simple HTTP GET request using a native HTTP library that runs // the request on a background thread. Future httpGet(String uri) async { @@ -26,16 +35,8 @@ Future httpGet(String uri) async { print('httpGet receiver get error $e $st'); }, ); - final sendPort = rp.sendPort; - final callback = NativeCallable.isolateGroupBound(( - Pointer responsePointer, - ) { - final typedList = responsePointer.cast().asTypedList( - responsePointer.length, - ); - final s = utf8.decode(typedList); - sendPort.send(s); - }); + final callback = NativeCallable.isolateGroupBound( + createGetSender(rp.sendPort)); // Invoke the native HTTP API. Our example HTTP library runs our GET // request on a background thread, and calls the callback on that same @@ -56,20 +57,22 @@ Future httpGet(String uri) async { @pragma('vm:shared') late int counter; -// Start a HTTP server on a background thread. -ReceivePort httpServe(void Function(String) onRequest) { - counter = 0; - final rp = ReceivePort(); - final callback = NativeCallable.isolateGroupBound(( - Pointer requestPointer, - ) { +Function (Pointer) createServeSender(SendPort sendPort) { + return (Pointer requestPointer) { counter++; final typedList = requestPointer.cast().asTypedList( requestPointer.length, ); - final s = utf8.decode(typedList); - rp.sendPort.send(s); - }); + sendPort.send(utf8.decode(typedList)); + }; +} + +// Start a HTTP server on a background thread. +ReceivePort httpServe(void Function(String) onRequest) { + counter = 0; + final rp = ReceivePort(); + final callback = NativeCallable.isolateGroupBound( + createServeSender(rp.sendPort)); rp.listen( (s) { print('httpServe counter: $counter');