flutter Zone区域

2021-03-04  本文已影响0人  liboxiang

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

区域的作用

以scheduleMicrotask的执行进行说明

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


flutter_zone.png

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

相关源码如下所示

//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;
  }
上一篇 下一篇

猜你喜欢

热点阅读