Tip: Consume Cursor as RxJava2 Iterable
1 min readJan 27, 2017
This is going to be really short tip how to iterate over Cursor
using RxJava. I promise!
In RxJava, we can emit items from Iterable
as Observable.fromArray()
. Cursor is structure that can be iterated, given his methods, but it does not implement Iterator
.
IteratingCursor
with Observable
will grant you opportunities to perform additional operation on the Cursor
data in the same call/thread/task.
For emitting items, in this case, moving internal position pointer of the Cursor
forwards, we need to create Iterable
that will do it:
- We need to move the
Cursor
whenIterator
hasNext() has been called. - Be careful, always check for
Cursor
not being closed. - Close the cursor, if you don’t need it anymore. (optional but recommended)
Example usage:
Observable.fromIterable(RxCursorIterable.from(cursor))....doAfterNext(new Consumer<Cursor>() {
@Override
public void accept(Cursor cursor) throws Exception {
if (cursor.getPosition() == cursor.getCount() - 1) {
cursor.close();
}
}
}).subscribe(new Consumer<Cursor>() {
@Override
public void accept(Cursor cursor) throws Exception {
//Do something. Cursor has been moved +1 position forward. }
});