简体   繁体   English

是否可以屈服于Dart的外部范围?

[英]Is it possible to yield to an outer scope in Dart?

Is it possible to somehow yield to an outer scope? 是否有可能以某种方式yield外部范围? Is there a more idiomatic approach that achieves the same intended result? 是否有更惯用的方法达到相同的预期结果?

Stream<T> fetch() async* {
  bool sentLiveValue = false;

  Future<T> cached = cache.fetchValue();
  cached.then((value) {
    if (!sentLiveValue)
      yield value; // Here, I want to yield to the outer scope.
  });

  await for (T value in liveValueSource.fetch()) {
    yield value;
    sentLiveValue = true;
    cache.update(value);
  }
}

If you're wondering about context, I'm implementing a data architecture with classes that can fetch data. 如果您想了解上下文,那么我正在使用一种可以fetch数据的类来实现数据体系结构。 The simplified code above should return a stream that first contains a cached value and then contains values from a live source. 上面的简化代码应返回一个流,该流首先包含一个缓存的值,然后包含来自实时源的值。

Note that if the cache is slower than the live data source (which is possible if the cache doesn't contain a value yet), the live data should be used first. 请注意,如果缓存比实时数据源慢(如果缓存尚不包含值,则有可能),应首先使用实时数据。 So await ing the cache value is not an option. 因此, await缓存值不是一种选择。

One solution is to use a StreamController , but beware: making your own streams is hazardous - you should handle listen, pause, resume and cancel. 一种解决方案是使用StreamController ,但要注意:制作自己的流很危险 -您应该处理监听,暂停,恢复和取消。

A partial implementation is: 部分实现是:

Stream<T> fetch<T>() {
  var sentLiveValue = false;
  var controller = StreamController<T>(
    onListen: () {},
    onPause: () {},
    onResume: () {},
    onCancel: () {},
  );

  cache.fetchValue().then((v) {
    if (!sentLiveValue) {
      controller.add(v);
    }
  });

  liveValueSource.fetch().listen(
    (t) {
      sentLiveValue = true;
      cache.update(t);
      controller.add(t);
    },
    onDone: () => controller.close(),
    onError: (e, st) => controller.addError(e, st),
  );

  return controller.stream;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM