-
-
Save yairkukielka/56e92958c711b3d05aa3 to your computer and use it in GitHub Desktop.
Pagination with RxJava
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.List; | |
import javax.xml.ws.Response; | |
import rx.Observable; | |
import rx.subjects.BehaviorSubject; | |
public final class Demo { | |
interface Response { | |
List<String> data(); | |
Observable<Response> next(); | |
} | |
public static void main(String... args) { | |
Observable<Response> call = createPaginatedCall(); | |
BehaviorSubject<Observable<Response>> subject = BehaviorSubject.create(call); | |
Observable<List<String>> pages = subject.flatMap(or -> or).map(r -> { | |
Observable<Response> next = r.next(); | |
if (next != null) { | |
subject.onNext(next); | |
} else { | |
subject.onCompleted(); | |
} | |
return r.data(); | |
}); | |
// Verify: | |
List<List<String>> paginated = pages.toList().toBlocking().first(); | |
System.out.println(paginated); | |
assert paginated.equals(Arrays.asList( | |
Arrays.asList("One", "Two", "Three"), | |
Arrays.asList("Four", "Five", "Six"), | |
Arrays.asList("Seven", "Eight", "Nine") | |
)); | |
} | |
private static Observable<Response> createPaginatedCall() { | |
List<String> data1 = Arrays.asList("One", "Two", "Three"); | |
List<String> data2 = Arrays.asList("Four", "Five", "Six"); | |
List<String> data3 = Arrays.asList("Seven", "Eight", "Nine"); | |
Response response3 = new DemoResponse(data3, null); | |
Response response2 = new DemoResponse(data2, Observable.just(response3)); | |
Response response1 = new DemoResponse(data1, Observable.just(response2)); | |
return Observable.just(response1); | |
} | |
static class DemoResponse implements Response { | |
private final List<String> data; | |
private final Observable<Response> next; | |
DemoResponse(List<String> data, Observable<Response> next) { | |
this.data = data; | |
this.next = next; | |
} | |
@Override public List<String> data() { | |
return data; | |
} | |
@Override public Observable<Response> next() { | |
return next; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment