flutter Zone区域

https://dart.dev/articles/archive/zones
zone.js: https://www.cnblogs.com/forcheng/p/13472326.html

区域的作用

  • 区域的最常见用途是处理异步执行的代码中引发的错误
  • 将数据(称为 区域局部值)与各个区域相关联。
  • 在部分或全部代码中覆盖一组有限的方法,例如print()和scheduleMicrotask()。
  • 每次代码进入或退出区域时,都要执行一个操作,例如启动或停止计时器,或保存堆栈跟踪。

以scheduleMicrotask的执行进行说明

scheduleMicrotask执行流程不一定是一下流程,此处只是举例其中一种情况说明Zone的作用


flutter_zone.png

假设scheduleMicrotask方法在zoneA中执行,则scheduleMicrotask方法的大致执行流程如下:

  • zoneA中调用scheduleMicrotask方法
  • zoneA.bindCallback对scheduleMicrotask的回调方法callback进行包装,将包装后的方法添加到MicroTask异步任务中
  • MicroTask queue执行zoneA.bindCallback的返回方法
  • 将Zone.current设置为zoneA
  • 执行callback
  • Zone.current恢复为zoneA之前的zone

相关源码如下所示

//class _CustomZone 
//_scheduleMicrotask由parent传递
void scheduleMicrotask(void f()) {
// this._scheduleMicrotask是_RootZone中的_scheduleMicrotask
    var implementation = this._scheduleMicrotask;
    ZoneDelegate parentDelegate = implementation.zone._parentDelegate;
    ScheduleMicrotaskHandler handler = implementation.function;
    return handler(implementation.zone, parentDelegate, this, f);
  }

//class _RootZone
_ZoneFunction<ScheduleMicrotaskHandler> get _scheduleMicrotask =>
      const _ZoneFunction<ScheduleMicrotaskHandler>(
          _rootZone, _rootScheduleMicrotask);

void _rootScheduleMicrotask(
    Zone? self, ZoneDelegate? parent, Zone zone, void f()) {
  if (!identical(_rootZone, zone)) {
    bool hasErrorHandler = !_rootZone.inSameErrorZone(zone);
    if (hasErrorHandler) {
      f = zone.bindCallbackGuarded(f);
    } else {
      f = zone.bindCallback(f);
    }
  }
  _scheduleAsyncCallback(f);
}

//真正添加移步操作的方法,将移步操作以链表形式存储起来
void _scheduleAsyncCallback(_AsyncCallback callback) {
  _AsyncCallbackEntry newEntry = new _AsyncCallbackEntry(callback);
  _AsyncCallbackEntry? lastCallback = _lastCallback;
  if (lastCallback == null) {
    _nextCallback = _lastCallback = newEntry;
    if (!_isInCallbackLoop) {
      _AsyncRun._scheduleImmediate(_startMicrotaskLoop);
    }
  } else {
    lastCallback.next = newEntry;
    _lastCallback = newEntry;
  }
}

//class _RootZone
//对f()进行包装,保证f在this(Zone)的上下文执行
ZoneCallback<R> bindCallback<R>(R f()) {
    return () => this.run<R>(f);
  }

R run<R>(R f()) {
    if (identical(Zone._current, _rootZone)) return f();
    return _rootRun(null, null, this, f);
  }

R _rootRun<R>(Zone? self, ZoneDelegate? parent, Zone zone, R f()) {
  if (identical(Zone._current, zone)) return f();

  if (zone is! _Zone) {
    throw ArgumentError.value(zone, "zone", "Can only run in platform zones");
  }

  _Zone old = Zone._enter(zone);
  try {
    return f();
  } finally {
    Zone._leave(old);
  }
}

static _Zone _enter(_Zone zone) {
    assert(!identical(zone, _current));
    _Zone previous = _current;
    _current = zone;
    return previous;
  }

static void _leave(_Zone previous) {
    assert(previous != null);
    Zone._current = previous;
  }

推荐阅读更多精彩内容