以飞镖安全性暂停流 [英] Pausing a stream in dart null safety

查看:44
本文介绍了以飞镖安全性暂停流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Dart代码转换为nnbd.

I'm converting dart code to nnbd.

我有以下代码.


   var subscription = response.listen(
        (newBytes) async {
          /// if we don't pause we get overlapping calls from listen
          /// which causes the [writeFrom] to fail as you can't
          /// do overlapping io.
          subscription.pause();

          /// we have new data to save.
          await raf.writeFrom(newBytes);
          subscription.resume();

        });

问题是出现以下错误:

The non-nullable local variable 'subscription' must be assigned before it can be used.
Try giving it an initializer expression, or ensure that it's assigned on every execution path.

我在这里也解决了类似的问题: dart-使用空安全协议时订阅的正确编码模式吗?@lrn

I've had a similar problem solved here: dart - correct coding pattern for subscription when using null saftey? which was answered by @lrn

但是在这种情况下,模式解决方案模式似乎不起作用.

However the pattern solution pattern doesn't seem to work in this case.

raf.writeFrom是一个异步操作,因此我必须使用异步"方法,这意味着我无法使用"forEach"解决方案,因为我再次无法访问订阅对象.

raf.writeFrom is an async operation so I must use an 'async' method which means I can't use the 'forEach' solution as again I don't have access to the subscription object.

推荐答案

我认为您的代码在之前无效之前也是合法的;您不能在声明变量之前引用变量( subscription ),并且声明要等到表达式用( response.listen(...))进行评估.您需要将声明与初始化分开,以打破循环依赖关系:

I don't think your code, as written, was legal before null-safety either; you can't reference a variable (subscription) before it's declared, and the declaration isn't complete until after the expression you initialize it with (response.listen(...)) is evaluated. You will need to separate the declaration from the initialization to break the circular dependency:

StreamSubscription<List<int>> subscription;
subscription = response.listen(...);

这篇关于以飞镖安全性暂停流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆