Skip to content

stream improvment - page splitter #296

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/main/java/org/gitlab4j/api/Pager.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
Expand Down Expand Up @@ -333,4 +334,12 @@ public Stream<T> stream() throws GitLabApiException {

return (streamBuilder.build());
}

public Stream<T> lazyStream() {
// Make sure that current page is 0, this will ensure the whole list is streamed
// regardless of what page the instance is currently on.
currentPage = 0;

return StreamSupport.stream(new PagerSpliterator<T>(this), false);
}
}
47 changes: 47 additions & 0 deletions src/main/java/org/gitlab4j/api/PagerSpliterator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package org.gitlab4j.api;

import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;

class PagerSpliterator<T> implements Spliterator<T> {

private Pager<T> pager;

private Iterator<T> elements;

PagerSpliterator(Pager<T> pager) {
this.pager = pager;
if (pager.hasNext()) {
elements = this.pager.next().iterator();
}
}

@Override
public boolean tryAdvance(Consumer<? super T> action) {
if (elements.hasNext()) {
action.accept(elements.next());
return true;
} else if (pager.hasNext()) {
elements = pager.next().iterator();
action.accept(elements.next());
return true;
}
return false;
}

@Override
public Spliterator<T> trySplit() {
return null;
}

@Override
public long estimateSize() {
return pager.getTotalItems();
}

@Override
public int characteristics() {
return 0;
}
}