Dart StreamController().stream 等于通过 == 相等,但不等于通过 identical。

huangapple go评论58阅读模式
英文:

Dart StreamController().stream equals by == but not by identical

问题

我发现了一个令人困惑的 Dart `Stream` 相等性行为。

```dart
final streamController = StreamController<int>();

final stream1 = streamController.stream;
final stream2 = streamController.stream;

print(stream1 == stream2); // 打印 true
print(identical(stream1, stream2)); // 打印 false

如果 stream2 引用了 stream1,则会按预期工作:

final streamController = StreamController<int>();

final stream1 = streamController.stream;
final stream2 = stream1;

print(stream1 == stream2); // 打印 true
print(identical(stream1, stream2)); // 打印 true

对于 StreamController<int>.broadcast(),一切都是相同的。对于这种令人困惑的行为,有什么解释呢?


<details>
<summary>英文:</summary>

I found out a confusing Dart `Stream` equality behavior.

```dart
final streamController = StreamController&lt;int&gt;();

final stream1 = streamController.stream;
final stream2 = streamController.stream;

print(stream1 == stream2); // Prints true
print(identical(stream1, stream2)); // Prints false

If the stream2 refers to the stream1, it works as expected:

final streamController = StreamController&lt;int&gt;();

final stream1 = streamController.stream;
final stream2 = stream1;

print(stream1 == stream2); // Prints true
print(identical(stream1, stream2)); // Prints true

It all works the same with a StreamController&lt;int&gt;.broadcast(). What would be the explanation for this confusing behavior?

答案1

得分: 2

stream 是一个 getter,它每次都可以返回相同的对象,但也可以像在这种情况下一样为每次调用创建新的对象。请查看dart/lib/async/stream_controller.dart

      // 每次都返回一个新的流。这些流是相等的,但不是相同的。
      Stream&lt;T&gt; get stream =&gt; _ControllerStream&lt;T&gt;(this);

评论解释了这种令人困惑的行为。

dart/lib/async/broadcast_stream_controller.dart中也发生了相同的情况:

      Stream&lt;T&gt; get stream =&gt; new _BroadcastStream&lt;T&gt;(this);
英文:

As stream is a getter it can return same object every time but can also create objects for each call like in this case. Take a look at dart/lib/async/stream_controller.dart:

      // Return a new stream every time. The streams are equal, but not identical.
      Stream&lt;T&gt; get stream =&gt; _ControllerStream&lt;T&gt;(this);

Comment explains this confusing behavior.

Same thing happens in dart/lib/async/broadcast_stream_controller.dart

      Stream&lt;T&gt; get stream =&gt; new _BroadcastStream&lt;T&gt;(this);

huangapple
  • 本文由 发表于 2023年7月17日 16:57:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702867.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定