3

When I use sqlbrite, I can't use the rxjava function toList() after using groupBy(). Here is my code:

QueryObservable query = jetAnywhereDB.createQuery(Item.TABLE, "SELECT * FROM testTable");
query.flatMap(q -> {
  return q.asRows(Item.MAPPER);
}).
groupBy(item -> {
  return Character.toUpperCase(item.name.charAt(0));
}).
subscribe(groupedObservable -> {
  groupedObservable.subscribe(item -> {
    Log.d("test", groupedObservable.getKey() + ": " + item.name);
  });
});

This works fine and logs all the items as they get emitted, but if I change it to

groupedObservable.toList().subscribe(items -> {
    Log.d("test", groupedObservable.getKey() + ": " + items);
  });

Am I not using toList() correctly? Could this be because the sqlbrite stream doesn't end so rxjava is waiting for more items to emit before completing the toList()?

Fahim Karim
  • 81
  • 1
  • 3

1 Answers1

1

The groupBy is a special kind of operator that requires you to subscribe to the returned GroupedObservable otherwise it won't request more data and will hang. In your first example, you do this but in the second, you start accumulating the groups without subscribing to them.

What you could do is flatMapping the groups into a pair of key and list so it won't hang:

.groupBy(t -> ...)
.flatMap(g -> g.toList().map(lst -> Pair.of(g.getKey(), lst)))
.subscribe(...)

I'm not familiar with SQLBrite but it is true a non-completing source with toList applied to it will never emit anything (regardless if there is a groupBy or not).

akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • So it looks like onComplete is never called for sqlbrite (https://github.com/square/sqlbrite/issues/36). Is there a way to use groupBy in that case? – Fahim Karim Oct 20 '15 at 13:58
  • 1
    If you consume `groupBy` then yes, but `toList` will not work. You have to stop the source either via `timeout()` or do time-bound `buffer()` instead of `toList`. – akarnokd Oct 20 '15 at 14:26
  • Should be accepted answer. Hot-cold thing is painful sometimes – ar-g Mar 11 '16 at 14:57