[embedder] Attach async::Loop after RunFlutterApp.

Change-Id: I4285aea4cca8fea82bf786a79d822bd0cb715667
diff --git a/src/embedder/main.cc b/src/embedder/main.cc
index 2695304..0f0739d 100644
--- a/src/embedder/main.cc
+++ b/src/embedder/main.cc
@@ -210,7 +210,7 @@
       .component_context = sys::ComponentContext::Create(),
   };
 
-  // Note: Serving the component context must happen after RunFlutterApp
+  // Serving the component context must happen after RunFlutterApp
   // because the embedder platform has a hack that adds inspect data into the
   // Dart VM using the component context
   // (https://github.com/flutter/engine/pull/33472).
@@ -218,6 +218,17 @@
     return EXIT_FAILURE;
   }
 
+  // Attaching the async loop to the current thread must happen
+  // immediately after RunFlutterApp to ensure that bindings in the embedder
+  // use the embedder's dispatcher to send requests instead of the Dart VM's
+  // dispatcher.
+  //
+  // Bindings created in the embedder before this line will never get fired.
+  //
+  // TODO(https://fxbug.dev/75282): Remove the logic in the Dart VM that sets its
+  // own default dispatcher to reduce the amount of global state.
+  async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
+
   // Necessary to get Flutter to render frames.
   FlutterWindowMetricsEvent window_metrics_event = {
       .struct_size = sizeof(FlutterWindowMetricsEvent),
@@ -275,16 +286,12 @@
 
   // Our run loop's dispatcher must be used to serve the component context in
   // order for requests' handlers to get called while we're looping.
-  async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
   status = embedder.component_context->outgoing()->ServeFromStartupInfo(loop.dispatcher());
   if (status != ZX_OK) {
     FX_LOGF(ERROR, embedder::kLogTag, "Failed to serve component context: %s",
             zx_status_get_string(status));
   }
 
-  // The loop must be configured before we create the SoftwareSurfaceProducer
-  // which connects to services.
-  // TODO(akbiggs): Inject these into the constructor instead.
   embedder.software_surface_producer = std::make_unique<embedder::SoftwareSurfaceProducer>();
 
   // Loop until we're done.