Running a stream using isolate in Flutter

1.5k Views Asked by At

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;
  }
}
0

There are 0 best solutions below