The toSortedList
operator behaves much like toList
except that it sorts the
resulting list. By default it sorts the list naturally in ascending order by means of the
Comparable
interface. If any of the items emitted by the Observable does not support
Comparable
with respect to the type of every other item emitted by the Observable,
toSortedList
will throw an exception. However, you can change this default behavior by also
passing in to toSortedList
a function that takes as its parameters two items and returns a
number; toSortedList
will then use that function instead of Comparable
to sort
the items.
For example, the following code takes a list of unsorted integers, converts it into an Observable, then
converts that Observable into one that emits the original list in sorted form as a single item:
Sample Code
numbers = Observable.from([8, 6, 4, 2, 1, 3, 5, 7, 9]);
numbers.toSortedList().subscribe(
{ println(it); }, // onNext
{ println("Error: " + it.getMessage()); }, // onError
{ println("Sequence complete"); } // onCompleted
);
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sequence complete
Here is an example that provides its own sorting function: in this case, one that sorts numbers according
to how close they are to the number 5.
numbers = Observable.from([8, 6, 4, 2, 1, 3, 5, 7, 9]);
numbers.toSortedList({ n, m -> Math.abs(5-n) - Math.abs(5-m) }).subscribe(
{ println(it); }, // onNext
{ println("Error: " + it.getMessage()); }, // onError
{ println("Sequence complete"); } // onCompleted
);
[5, 6, 4, 3, 7, 8, 2, 1, 9]
Sequence complete
toSortedList
does not by default operate on any particular
Scheduler.