Optionally map a SqlBrite.Query to an Observable #45
Conversation
I was thinking about this on the plane today, what if we return a subclass of db.createQuery("SELECT * FROM users", "users")
.mapToModel(User.MAP)
.toList()
.subscribe(adapter); |
Not sure that will work - |
Ah, right. Well it can just be db.createQuery("SELECT * FROM users", "users") // Observable<Cursor>
.mapToModel(User.MAP) // Observable<List<User>>
.subscribe(adapter); then. |
public <T> Observable<List<T>> mapToModel(final Func1<Cursor, T> func) {
return lift(new Observable.Operator<List<T>, Query>() {
@Override public Subscriber<? super Query> call(final Subscriber<? super List<T>> subscriber) {
return new Subscriber<Query>(subscriber) {
@Override public void onNext(Query query) {
Cursor cursor = query.run();
List<T> items;
try {
items = new ArrayList<>(cursor.getCount());
while (cursor.moveToNext()) {
items.add(func.call(cursor));
}
} finally {
cursor.close();
}
subscriber.onNext(items);
}
@Override public void onCompleted() {
subscriber.onCompleted();
}
@Override public void onError(Throwable e) {
subscriber.onError(e);
}
};
}
});
} |
|
By going straight into the list it's removing a lot of potential functionality that this whole PR was intended to help add. Some examples:
Or say you want to
but I think we should be helping out the other case. Plus then we're not composing a list, splitting it out, and composing it back together again. |
Ah, right right. The conversation is coming back to me now. |
We should still do a |
while (cursor.moveToNext()) { | ||
subscriber.onNext(map.call(cursor)); | ||
} | ||
subscriber.onCompleted(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Call this outside the try
so if close()
throws it'll go to onError
Yup definitely. Plus since they're taking the same |
* | ||
* @param map Takes in a cursor for a single row and maps it to your desired result type. | ||
*/ | ||
public <T> Observable<T> map(final Func1<Cursor, T> map) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
final
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't know how I feel about overloading map
... Maybe "asRows" or "toRows" or something?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
makes sense, map makes it sound like you're mapping the whole query to something. asRows
sounds good.
LGTM |
Optionally map a SqlBrite.Query to an Observable
No description provided.