I have an RXJava 2 observer that emits objects of type somethingWithDate
. These objects have a property that contains a java date object as well as a boolean isHeader
.
What I need to do with these objects is:
- Group them by month and year (all dates in January of 2017, all dates in January of 2016, all dates in February 2016, ...)
- Add a header (also a
somethingWithDate
) at the start of the group - Sort groups in regard to each other (by date, sorting inside the groups would be nice too but not needed, the header needs to stay at first position in each group)
- Merged(?) all elements from all groups back into one list of elements
single<List<somethingWithDate>>
Here is an example (all objects of type somethingWithDate
, but I will only display the important properties here to make it more readable):
Input Data:
1.1.2017, 2.1.2017, 1.1.2016, 8.8.2017
Result:
header, 1.1.2016, header, 1.1.2017, 2.1.2017, header, 8.8.2017
I know 1. can be achieved by using groupBy()
. I haven't found a way to do 2 though. I also know there is a toList()
and toSortedList()
to maybe use for 3. and 4. but I am unsure how that works with the groups from the groupBy()
and how I can collect them back in one list.
Pseudocode:
inputListObserver
.groupBy(obj.date.year + obj.date.month)
.map(group -> group.addAtBeginning(headerElement))
.sortBy(groupKey)
.mergeToList()
...
I think I finally found an answer. Using flatmap (thanks for the idea @masps)seems to do the trick. Here is the pseudo code:
I would use a
ConnectableObservable
to share the emissions of the initial stream. With this pseudocode you have 3 sorted streams by year with a header.