简体   繁体   English

在Dart中,仅在回调内部存在的集合/列表上“屈服”的最佳方法是什么?

[英]What is the best way to `yield` over a collection/list that only exists inside of a callback, in Dart?

I have a method ( _all ) that has a callback ( _runInTxn ) inside. 我有一个方法( _all ,有一个回调() _runInTxn )内。 The callback gets the list ( rs ) that I would like to yield over and return via _all's Stream. 回调获取我想yield的列表( rs )并通过_all的Stream返回。 However, the callback isn't marked with async* (but the method is marked as async* ). 但是,该回调未标记为async* (但该方法标记为async* )。

What is the best way to yield over a collection/list that only exists inside of a callback? yield仅在回调内部存在的集合/列表的最佳方法是什么?

Here is an example of what is correct and works: 这是正确且有效的示例:

  Stream<String> _all() async* {
    var sql = 'SELECT id,value FROM $storeName';
    SqlResultSet resultSet;

    await _runInTxn((txn) {
      txn.executeSql(sql, [], (txn, rs) {
        resultSet = rs;
      });
    });

    for (var i = 0; i < resultSet.rows.length; ++i) {
      var row = resultSet.rows.item(i);
      yield row['value'];
    }
  }

I'm curious if there's a better way to write this code, so I can avoid a null resultSet . 我很好奇是否有更好的方法编写此代码,因此可以避免使用null resultSet I'd really love to have my yield statement inside of the executeSql statement. 我真的很想将我的yield语句放在executeSql语句中。 Can I do a "non-local yield" ? 我可以做“非本地收益”吗?

There was a similar discussion about using yield inside Future.forEach() and the answer was as far as I remember that this is not supported (couldn't find the discussion yet). 关于在Future.forEach()使用yield讨论类似,据我所知,答案还不受支持(目前尚未找到讨论)。

I guess it would be easier without async* 我想没有async *会更容易

Stream<String> _all() {
  var sql = 'SELECT id,value FROM $storeName';
  var sc = new StreamController<String>();

  _runInTxn((txn) {
    txn.executeSql(sql, [], (txn, rs) {
      rs.rows.forEach((row) => sc.add(row['value']));
    });
  }).then((_) => sc.close());

  return sc.stream;
}

try at DartPad 尝试DartPad

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

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