英文:
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<int>();
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<int>();
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<int>.broadcast()
. What would be the explanation for this confusing behavior?
答案1
得分: 2
如 stream
是一个 getter,它每次都可以返回相同的对象,但也可以像在这种情况下一样为每次调用创建新的对象。请查看dart/lib/async/stream_controller.dart:
// 每次都返回一个新的流。这些流是相等的,但不是相同的。
Stream<T> get stream => _ControllerStream<T>(this);
评论解释了这种令人困惑的行为。
在dart/lib/async/broadcast_stream_controller.dart中也发生了相同的情况:
Stream<T> get stream => new _BroadcastStream<T>(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<T> get stream => _ControllerStream<T>(this);
Comment explains this confusing behavior.
Same thing happens in dart/lib/async/broadcast_stream_controller.dart
Stream<T> get stream => new _BroadcastStream<T>(this);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论