Skip to content

Commit

Permalink
Override first, last and single on RealmResults
Browse files Browse the repository at this point in the history
Avoid instantiating a _RealmResultsIterator for first and
single calls, and avoid iterating the entire collection for last.
  • Loading branch information
nielsenko committed Jun 12, 2023
1 parent 410c95a commit 1da0554
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions lib/src/results.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
//
////////////////////////////////////////////////////////////////////////////////
import 'dart:async';
import 'dart:collection' as collection;
import 'dart:ffi';

import 'collections.dart';
Expand All @@ -28,7 +27,7 @@ import 'realm_object.dart';
/// added to or deleted from the Realm that match the underlying query.
///
/// {@category Realm}
class RealmResults<T extends Object?> extends collection.IterableBase<T> with RealmEntity implements Finalizable {
class RealmResults<T extends Object?> extends Iterable<T> with RealmEntity implements Finalizable {
final RealmObjectMetadata? _metadata;
final RealmResultsHandle _handle;

Expand Down Expand Up @@ -56,11 +55,9 @@ class RealmResults<T extends Object?> extends collection.IterableBase<T> 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<T> get iterator {
var results = this;
Expand All @@ -71,10 +68,23 @@ class RealmResults<T extends Object?> extends collection.IterableBase<T> 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<T> freeze() {
if (isFrozen) {
Expand Down

0 comments on commit 1da0554

Please sign in to comment.