Skip to content

Commit 75bc45a

Browse files
committed
BreakForEach for Query.forEach()
1 parent 4496d52 commit 75bc45a

3 files changed

Lines changed: 29 additions & 2 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package io.objectbox.query;
2+
3+
/**
4+
* You can throw this inside a {@link QueryConsumer} to signal {@link Query#forEach(QueryConsumer)} should "break".
5+
* This will stop consuming any further data.
6+
*/
7+
public class BreakForEach extends RuntimeException {
8+
}

objectbox-java/src/main/java/io/objectbox/query/Query.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,10 +210,14 @@ public void run() {
210210
if (entity == null) {
211211
throw new IllegalStateException("Internal error: data object was null");
212212
}
213-
if(eagerRelations != null) {
213+
if (eagerRelations != null) {
214214
resolveEagerRelationForNonNullEagerRelations(entity, i);
215215
}
216-
consumer.accept(entity);
216+
try {
217+
consumer.accept(entity);
218+
} catch (BreakForEach breakForEach) {
219+
break;
220+
}
217221
}
218222
}
219223
});

tests/objectbox-java-test/src/main/java/io/objectbox/query/QueryTest.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,21 @@ public void accept(TestEntity data) {
368368
assertEquals(testEntities.size() + 1, box.count());
369369
}
370370

371+
@Test
372+
public void testForEachBreak() {
373+
putTestEntitiesStrings();
374+
final StringBuilder stringBuilder = new StringBuilder();
375+
box.query().startsWith(simpleString, "banana").build()
376+
.forEach(new QueryConsumer<TestEntity>() {
377+
@Override
378+
public void accept(TestEntity data) {
379+
stringBuilder.append(data.getSimpleString());
380+
throw new BreakForEach();
381+
}
382+
});
383+
assertEquals("banana", stringBuilder.toString());
384+
}
385+
371386
private List<TestEntity> putTestEntitiesScalars() {
372387
return putTestEntities(10, null, 2000);
373388
}

0 commit comments

Comments
 (0)