From 1da0554b17d74e124770f140db1081f4bcb4053d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kasper=20Overg=C3=A5rd=20Nielsen?= Date: Mon, 8 May 2023 11:25:34 +0200 Subject: [PATCH] Override first, last and single on RealmResults Avoid instantiating a _RealmResultsIterator for first and single calls, and avoid iterating the entire collection for last. --- lib/src/results.dart | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/src/results.dart b/lib/src/results.dart index a90a440fe4..210a6d9d27 100644 --- a/lib/src/results.dart +++ b/lib/src/results.dart @@ -16,7 +16,6 @@ // //////////////////////////////////////////////////////////////////////////////// import 'dart:async'; -import 'dart:collection' as collection; import 'dart:ffi'; import 'collections.dart'; @@ -28,7 +27,7 @@ import 'realm_object.dart'; /// added to or deleted from the Realm that match the underlying query. /// /// {@category Realm} -class RealmResults extends collection.IterableBase with RealmEntity implements Finalizable { +class RealmResults extends Iterable with RealmEntity implements Finalizable { final RealmObjectMetadata? _metadata; final RealmResultsHandle _handle; @@ -56,11 +55,9 @@ class RealmResults extends collection.IterableBase with Re } } - /// `true` if the `Results` collection is empty. @override bool get isEmpty => length == 0; - /// Returns a new `Iterator` that allows iterating the elements in this `RealmResults`. @override Iterator get iterator { var results = this; @@ -71,10 +68,23 @@ class RealmResults extends collection.IterableBase with Re return _RealmResultsIterator(results); } - /// The number of values in this `Results` collection. @override int get length => realmCore.getResultsCount(this); + @override + T get first => this[0]; + + @override + T get last => this[length - 1]; + + @override + T get single { + if (length != 1) { + throw StateError('Expected exactly one element but was $length'); + } + return this[0]; + } + /// Creates a frozen snapshot of this query. RealmResults freeze() { if (isFrozen) {