Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using groupBy and toList rxjava functions with sqlbrite

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()?

like image 995
Fahim Karim Avatar asked Jul 28 '26 00:07

Fahim Karim


1 Answers

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).

like image 183
akarnokd Avatar answered Jul 29 '26 16:07

akarnokd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!