Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Started handling messages from background isolates. #109005

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 9, 2022

Conversation

gaaclarke
Copy link
Member

@gaaclarke gaaclarke commented Aug 4, 2022

companion engine pr: flutter/engine#35174
design doc: https://docs.google.com/document/d/1yAFw-6kBefuurXWTur9jdEUAckWiWJVukP1Iay8ehyU/edit#
issue: #13937

example

main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:isolate';

void isolateMain(BackgroundIsolateBinding binding) async {
  BackgroundIsolateBinding.initializeBackgroundIsolate(binding);
  const BasicMessageChannel channel =
      BasicMessageChannel('dev.flutter.aaclarke.echo', StandardMessageCodec());
  final String result = await channel.send('hello');
  print(result);
}

void main() {
  final BackgroundIsolateBinding binding =
      BackgroundIsolateBinding.initializeRootIsolate();
  Isolate.spawn(isolateMain, binding);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Isolate Platform Channels'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(),
    );
  }
}

AppDelegate.swift

import UIKit
import Flutter
import os.log

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    let registrar = self.registrar(forPlugin: "echo");
    let channel = FlutterBasicMessageChannel(name: "dev.flutter.aaclarke.echo", binaryMessenger: registrar!.messenger());
    channel.setMessageHandler { (input, reply) in
      if let input_string = input as? String? {
        os_log("%@", input_string ?? "null");
      } else {
        os_log("unrecognized message");
      }
      reply(input)
    }
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Pre-launch Checklist

  • I read the Contributor Guide and followed the process outlined there for submitting PRs.
  • I read the Tree Hygiene wiki page, which explains my responsibilities.
  • I read and followed the Flutter Style Guide, including Features we expect every widget to implement.
  • I signed the CLA.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///).
  • I added new tests to check the change I am making, or this PR is test-exempt.
  • All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel on Discord.

@flutter-dashboard flutter-dashboard bot added the framework flutter/packages/flutter repository. See also f: labels. label Aug 4, 2022
@gaaclarke gaaclarke force-pushed the isolate-platform-channels branch 6 times, most recently from 563a5e3 to 8cce92e Compare August 12, 2022 17:26
@gaaclarke gaaclarke force-pushed the isolate-platform-channels branch 3 times, most recently from a18df55 to 7c5cc9a Compare August 12, 2022 22:20
@Hixie
Copy link
Contributor

Hixie commented Aug 15, 2022

The overall idea seems fine. I'm not sure I understand the specifics of the implementation on the Dart side. Maybe we can go over the PR together on VC?

@Hixie
Copy link
Contributor

Hixie commented Aug 18, 2022

@gaaclarke here's a proposed reworking of the API as discussed in our chat:
master...Hixie:flutter:isolate-platform-channels

It's semantically equivalent to the original code, just presented differently.

@gaaclarke gaaclarke force-pushed the isolate-platform-channels branch from f516ee3 to c7dbcde Compare August 19, 2022 01:00
@gaaclarke
Copy link
Member Author

@gaaclarke here's a proposed reworking of the API as discussed in our chat: master...Hixie:flutter:isolate-platform-channels

It's semantically equivalent to the original code, just presented differently.

Thanks, I've incorporated most of it now to see how it worked out. I still need to clean it up and incorporate your docs. I made 2 changes:

  1. Not requiring the binary messenger in the channel constructor as we discussed in 04194fd#commitcomment-81568761
  2. I put the logic for acquiring the the RootIsolateToken on that class and started exporting it from services/platform_channels.dart. I wanted to make sure that importing services was sufficient to allowing one to use platform channels on background isolates.

ui.PlatformDispatcher.instance.registerBackgroundIsolate(token);
final BackgroundIsolateBinaryMessenger portBinaryMessenger = BackgroundIsolateBinaryMessenger();
_backgroundIsolateBinaryMessenger = portBinaryMessenger;
portBinaryMessenger.receivePort.listen((dynamic message) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i would advise using the pattern i had on my branch to make this a static method rather than a closure. That'll avoid accidentally closing over things we don't want to close over, but also generally the code will be easier to reason about (and it makes the satisfying pattern of having both the send and the receive logic be parallel).

@gaaclarke gaaclarke requested a review from Hixie September 9, 2022 17:36
@flutter-dashboard

This comment was marked as resolved.

@flutter-dashboard flutter-dashboard bot added the a: tests "flutter test", flutter_test, or one of our tests label Sep 9, 2022
@gaaclarke
Copy link
Member Author

It looks like this pull request may not have tests. Please make sure to add tests before merging. If you need an exemption to this rule, contact Hixie on the #hackers channel in Chat (don't just cc him here, he won't see it! He's on Discord!).

False positive, there are integration tests.

Copy link
Contributor

@dnfield dnfield left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@gaaclarke gaaclarke merged commit 0d19d46 into flutter:master Sep 9, 2022
@gaaclarke
Copy link
Member Author

Over the course of responding to feedback I broke the integration test which apparently doesn't run as a presubmit. Reverting to open the tree.

@gaaclarke gaaclarke added revert Autorevert PR (with "Reason for revert:" comment) and removed revert Autorevert PR (with "Reason for revert:" comment) labels Sep 9, 2022
gaaclarke added a commit that referenced this pull request Sep 9, 2022
engine-flutter-autoroll added a commit to engine-flutter-autoroll/packages that referenced this pull request Sep 10, 2022
engine-flutter-autoroll added a commit to engine-flutter-autoroll/plugins that referenced this pull request Sep 10, 2022
engine-flutter-autoroll added a commit to engine-flutter-autoroll/plugins that referenced this pull request Sep 10, 2022
engine-flutter-autoroll added a commit to engine-flutter-autoroll/plugins that referenced this pull request Sep 11, 2022
engine-flutter-autoroll added a commit to engine-flutter-autoroll/plugins that referenced this pull request Sep 12, 2022
engine-flutter-autoroll added a commit to engine-flutter-autoroll/plugins that referenced this pull request Sep 12, 2022
engine-flutter-autoroll added a commit to engine-flutter-autoroll/plugins that referenced this pull request Sep 12, 2022
engine-flutter-autoroll added a commit to engine-flutter-autoroll/plugins that referenced this pull request Sep 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
a: tests "flutter test", flutter_test, or one of our tests c: contributor-productivity Team-specific productivity, code health, technical debt. framework flutter/packages/flutter repository. See also f: labels.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants