From 2a7a185f1e6418ce8356eed11a5978b0acf3faf5 Mon Sep 17 00:00:00 2001
From: Matthew Fosse <matt@fosse.co>
Date: Thu, 25 Jul 2024 09:03:40 -0500
Subject: [PATCH] potential mweb sync fix (ios)

---
 cw_mweb/lib/cw_mweb.dart | 27 +++++++++++++++++++--------
 1 file changed, 19 insertions(+), 8 deletions(-)

diff --git a/cw_mweb/lib/cw_mweb.dart b/cw_mweb/lib/cw_mweb.dart
index 765ba7911..c464930f5 100644
--- a/cw_mweb/lib/cw_mweb.dart
+++ b/cw_mweb/lib/cw_mweb.dart
@@ -4,20 +4,31 @@ import 'cw_mweb_platform_interface.dart';
 import 'mwebd.pbgrpc.dart';
 
 class CwMweb {
+  static RpcClient? _rpcClient;
+  static ClientChannel? _clientChannel;
+
   static Future<RpcClient> stub() async {
     final appDir = await getApplicationSupportDirectory();
     int port = await CwMwebPlatform.instance.start(appDir.path) ?? 0;
-    return RpcClient(
-      ClientChannel('127.0.0.1',
-          port: port,
-          options: const ChannelOptions(
-            credentials: ChannelCredentials.insecure(),
-            keepAlive: ClientKeepAliveOptions(permitWithoutCalls: true),
-          )),
-    );
+    _clientChannel = ClientChannel('127.0.0.1',
+        port: port,
+        options: const ChannelOptions(
+          credentials: ChannelCredentials.insecure(),
+          keepAlive: ClientKeepAliveOptions(permitWithoutCalls: true),
+        ));
+    _rpcClient = RpcClient(_clientChannel!);
+    return _rpcClient!;
   }
 
   static Future<void> stop() async {
     await CwMwebPlatform.instance.start("stop");
+    await cleanup();
+  }
+
+  static Future<void> cleanup() async {
+    await _clientChannel?.terminate();
+    _rpcClient = null;
+    _clientChannel = null;
+    print("rpc has been shut down");
   }
 }