使用分离株在颤动中运行流

发布于 2025-02-03 08:56:59 字数 3374 浏览 5 评论 0原文

我想在单独的分离株中运行流。另外,我需要通过该流中的价值变化通知主分离株。为了做到这一点,我将把流返回到主分离株。
我试图在

import 'dart:async';
import 'dart:isolate';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

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

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key,}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  final ConnectivityChecker _connectivityChecker = ConnectivityChecker();
  bool _isConnected = true;


  @override
  void initState() {
    super.initState();
    //here the main isolate want to see the stream's value
    _connectivityChecker.subscribe((isConnected) => _check(isConnected));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _isConnected ? 'Connected' : 'Disconnected',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
    );
  }

  Future<bool> _check(bool isConnected) {
    setState(()=> _isConnected = isConnected);
    return Future.value(isConnected);
  }
}

void isolateTask(_Message message) {
  message.connectivity.onConnectivityChanged.listen(
        (connectivity) => message.sendPort.send(connectivity),
  );
}


class ConnectivityChecker {
  ConnectivityChecker();

  final Connectivity _connectivity = Connectivity();
  final StreamController<bool> onConnectivityChanged =
  StreamController();

  StreamSubscription<bool> subscribe(
      Future<bool> Function(bool isConnected) task,
      ) {
    final ReceivePort _receivePort = ReceivePort();
    Isolate? isolate;

    //Start spawned isolate
    Future.microtask(() async {
      isolate = await Isolate.spawn(
        isolateTask,
        _Message(_receivePort.sendPort, _connectivity),
      );
    });

    _receivePort.listen((message) {
      print(">>>>>>${message.toString()}");
      onConnectivityChanged.add(message);
    });

    //notify the main isolate
    return onConnectivityChanged.stream.listen(
          (connectivity) => task(connectivity),
    );
  }
}

class _Message {
  _Message(
      this.sendPort,
      this.connectivity,
      );

  Connectivity connectivity;
  SendPort sendPort;
}

//this class is going to mock the connectivity changes
class Connectivity{
  final StreamController<bool> _controller = StreamController<bool>();
  bool _isConnected = false;

  Connectivity(){
    Timer.periodic(
      const Duration(seconds: 1),
          (Timer timer) {
        _isConnected = !_isConnected;
        onConnectivityChanged;
      },
    );
  }

  Stream<bool> get onConnectivityChanged {
    print(">>>>>>_isConnected: ${_isConnected.toString()}");
    _controller.add(_isConnected);
     return _controller.stream;
  }
}

I want to run a stream in a separate isolate. Also, I need the main isolate to be notified by the value changes in that stream. In order to do that, I'm going to return the stream to the main isolate.
I tried to solve the problem with the help of this code and here is my code but it notifies the main isolate only once. I don't know what is wrong with my code. I don't know much about isolates.

import 'dart:async';
import 'dart:isolate';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

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

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key,}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  final ConnectivityChecker _connectivityChecker = ConnectivityChecker();
  bool _isConnected = true;


  @override
  void initState() {
    super.initState();
    //here the main isolate want to see the stream's value
    _connectivityChecker.subscribe((isConnected) => _check(isConnected));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _isConnected ? 'Connected' : 'Disconnected',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
    );
  }

  Future<bool> _check(bool isConnected) {
    setState(()=> _isConnected = isConnected);
    return Future.value(isConnected);
  }
}

void isolateTask(_Message message) {
  message.connectivity.onConnectivityChanged.listen(
        (connectivity) => message.sendPort.send(connectivity),
  );
}


class ConnectivityChecker {
  ConnectivityChecker();

  final Connectivity _connectivity = Connectivity();
  final StreamController<bool> onConnectivityChanged =
  StreamController();

  StreamSubscription<bool> subscribe(
      Future<bool> Function(bool isConnected) task,
      ) {
    final ReceivePort _receivePort = ReceivePort();
    Isolate? isolate;

    //Start spawned isolate
    Future.microtask(() async {
      isolate = await Isolate.spawn(
        isolateTask,
        _Message(_receivePort.sendPort, _connectivity),
      );
    });

    _receivePort.listen((message) {
      print(">>>>>>${message.toString()}");
      onConnectivityChanged.add(message);
    });

    //notify the main isolate
    return onConnectivityChanged.stream.listen(
          (connectivity) => task(connectivity),
    );
  }
}

class _Message {
  _Message(
      this.sendPort,
      this.connectivity,
      );

  Connectivity connectivity;
  SendPort sendPort;
}

//this class is going to mock the connectivity changes
class Connectivity{
  final StreamController<bool> _controller = StreamController<bool>();
  bool _isConnected = false;

  Connectivity(){
    Timer.periodic(
      const Duration(seconds: 1),
          (Timer timer) {
        _isConnected = !_isConnected;
        onConnectivityChanged;
      },
    );
  }

  Stream<bool> get onConnectivityChanged {
    print(">>>>>>_isConnected: ${_isConnected.toString()}");
    _controller.add(_isConnected);
     return _controller.stream;
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文