Consider KeysetScrollPosition direction in WindowIterator.

We now consider the scroll direction in the iterator to properly continue Keyset backward scrolling.

Closes #2851
This commit is contained in:
Mark Paluch
2023-06-13 11:50:28 +02:00
parent 487795dcee
commit 05d68a0eab
2 changed files with 40 additions and 1 deletions

View File

@@ -19,6 +19,7 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
import org.springframework.data.domain.KeysetScrollPosition;
import org.springframework.data.domain.ScrollPosition;
import org.springframework.data.domain.Window;
import org.springframework.lang.Nullable;
@@ -92,7 +93,7 @@ public class WindowIterator<T> implements Iterator<T> {
if (currentWindow != null && currentWindow.hasNext()) {
currentPosition = currentWindow.positionAt(currentWindow.size() - 1);
currentPosition = getNextPosition(currentPosition, currentWindow);
currentIterator = null;
currentWindow = null;
continue;
@@ -113,6 +114,17 @@ public class WindowIterator<T> implements Iterator<T> {
return currentIterator.next();
}
private static ScrollPosition getNextPosition(ScrollPosition currentPosition, Window<?> window) {
if (currentPosition instanceof KeysetScrollPosition ksp) {
if (ksp.scrollsBackward()) {
return window.positionAt(0);
}
}
return window.positionAt(window.size() - 1);
}
/**
* Builder API to construct a {@link WindowIterator}.
*

View File

@@ -22,6 +22,7 @@ import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Function;
@@ -30,7 +31,9 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.data.domain.ScrollPosition.Direction;
import org.springframework.data.support.WindowIterator;
import org.springframework.data.util.Streamable;
/**
* Unit tests for {@link WindowIterator}.
@@ -127,4 +130,28 @@ class WindowIteratorUnitTests {
assertThat(capturedResult).containsExactly("a", "b", "c", "d");
}
@Test // GH-2151
void considersBackwardKeysetScrolling() {
Window<String> initial = Window.from(List.of("c", "d"),
value -> KeysetScrollPosition.of(Map.of("k", 10 + value), Direction.BACKWARD), true);
Window<String> terminal = Window.from(List.of("a", "b"),
value -> KeysetScrollPosition.of(Map.of("k", value), Direction.BACKWARD));
WindowIterator<String> iterator = WindowIterator.of(it -> {
if (it instanceof KeysetScrollPosition ksp) {
if (Integer.valueOf(10).equals(ksp.getKeys().get("k"))) {
return terminal;
}
}
return initial;
}).startingAt(ScrollPosition.keyset().backward());
List<String> items = Streamable.of(() -> iterator).toList();
assertThat(items).containsExactly("c", "d", "a", "b");
}
}