Nico Rodsevich
Nico Rodsevich

Reputation: 2575

How to properly implement a ZoneSpecification(fork: ) handler in Dart

When I try to implement a fork override for ZoneSpecifications like this:

runZoned(
() {
  runZoned(() {
    print('in zone');
  });
},
zoneSpecification: ZoneSpecification(
  fork: (self, parent, zone, specification, zoneValues) {
    print('forked!');
    return zone.fork(specification: specification, zoneValues: zoneValues);
  },
),

);

I only get this:

forked! (x7990)
forked!
Unhandled exception:
Stack Overflow
#0 _print (dart:_builtin:29:1)
...
#7993 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

On the code I read that only the RootZone contains the enter zone, so I'm lost on how to accomplish the task.

Upvotes: 1

Views: 73

Answers (1)

Dan R
Dan R

Reputation: 1252

The call to zone.fork in your handler fork and the nested runZoned seem to cause a recursive call to the fork handler and eventually a stackoverflow.

The example below uses the fork handler of the ZoneDelegate parent to create the fork and adds some zoneValues to help identify the zones:

import 'dart:async';

int id = 0;

void main(List<String> args) {
  runZoned(
      () {
        print(' ... Now in zone: ${Zone.current[#id]}');
        print('     parent zone: ${Zone.current.parent}');

        runZoned(
          () {
            print('     ... Now in zone: ${Zone.current[#id]}');
            print('         parent zone: ${Zone.current.parent![#id]}');
          },
          zoneValues: {#id: ++id},
        );
      },
      zoneValues: {#id: ++id},
      zoneSpecification: ZoneSpecification(fork: (
        self,
        parent,
        zone,
        specification,
        zoneValues,
      ) {
        print('     Forking zone with id: ${zone[#id]}');
        // Custom fork handler increments forked zone id by 100.
        return parent.fork(
          zone,
          specification,
          {#id: (zoneValues![#id] as int) + 100}, 
        );
      }));
}

The console output is listed below:

$ dart zone_example.dart 
... Now in zone: 1
     parent zone: Instance of '_RootZone'
     Forking zone with id: 1
     ... Now in zone: 102
         parent zone: 1

Upvotes: 1

Related Questions