integral_isolates 0.5.1 copy "integral_isolates: ^0.5.1" to clipboard
integral_isolates: ^0.5.1 copied to clipboard

The power of Dart's compute function, but using a long lived isolate.

example/main.dart

// ignore_for_file: avoid_print

import 'dart:io';

import 'package:integral_isolates/integral_isolates.dart';

void main() async {
  final isolated = StatefulIsolate();

  /// Function that halts the thread while looping and printing.
  Future<void> threadSleepComputation(int input) async {
    for (var i = 0; i < 15; i++) {
      print("Look, ma. I'm not stopped! ($input)");
      sleep(const Duration(milliseconds: 200));
    }
  }

  // Running two instances of the halting function [threadSleepComputation] and
  // an isolate at the same time.
  final pi = (await Future.wait<dynamic>([
    Future.delayed(
      const Duration(milliseconds: 100),
      () => threadSleepComputation(1),
    ),
    isolated.compute(leibnizPi, 500000000),
    Future.delayed(
      const Duration(milliseconds: 100),
      () => threadSleepComputation(2),
    ),
  ]))[1];

  print(pi);

  isolated.dispose();
}

/// Calculate PI and prints to log when done
double leibnizPi(int steps) {
  double x = 1.0;

  for (var i = 1; i < steps; i++) {
    if (i.isOdd) {
      x = x - (1.0 / ((2.0 * i) + 1));
    } else {
      x = x + (1.0 / ((2.0 * i) + 1));
    }
  }
  x = x * 4.0;
  print("Job's done!");
  return x;
}
36
likes
160
points
3.09k
downloads
screenshot

Publisher

verified publisherlohnn.se

Weekly Downloads

The power of Dart's compute function, but using a long lived isolate.

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

Dependencies

async, meta

More

Packages that depend on integral_isolates