Skip to content

Commit 3da5d6f

Browse files
committed
change the implementation to emit only on completion.
1 parent 4d4052f commit 3da5d6f

File tree

2 files changed

+21
-13
lines changed

2 files changed

+21
-13
lines changed

Playground/RxSwiftExtPlayground.playground/Pages/toSortedArray.xcplaygroundpage/Contents.swift

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,22 +18,27 @@ import RxSwiftExt
1818
*/
1919

2020
example("Ensure that only a sorted array is emitted") {
21-
let array1 = Observable.of([5, 4, 7, 8, 2, 6, 9, 0, 10])
22-
let array2 = Observable.of([10, 9, 12, 8, 4, 1, 1, 8, 14])
23-
24-
array1.toSortedArray()
21+
let sequenceStream = Observable.of(1...12)
22+
let array = Observable.of([10, 9, 12, 8, 4, 1, 1, 8, 14])
23+
24+
// Ascending order
25+
array.toSortedArray()
2526
.subscribe(onNext: { result in
2627
print(result)
2728
})
2829

29-
// Ascending order
30-
array2.toSortedArray(<)
30+
array.toSortedArray(<)
3131
.subscribe(onNext: { result in
3232
print(result)
3333
})
3434

3535
// Descending order
36-
array2.toSortedArray(>)
36+
sequenceStream.toSortedArray(>)
37+
.subscribe(onNext: { result in
38+
print(result)
39+
})
40+
41+
array.toSortedArray(>)
3742
.subscribe(onNext: { result in
3843
print(result)
3944
})

Source/RxSwift/toSortedArray.swift

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,22 @@ extension Observable where E: Sequence, E.Element: Comparable {
1717
- returns: The sorted observable.
1818
*/
1919
public func toSortedArray<T>(ascending: Bool = true)
20-
-> Observable<[T]> where E.Iterator.Element == T {
21-
return map {
22-
$0.sorted(by: { ascending ? $0 < $1 : $0 > $1 })
23-
}
20+
-> Observable<[T]> where E.Element == T {
21+
return toSortedArray({ ascending ? $0 < $1 : $0 > $1 })
2422
}
23+
2524
/**
2625
Transforms an observable of comparables into an observable of ordered arrays by using the function passed in.
2726

2827
- parameter areInIncreasingOrder: A function to compare to elements.
2928
- returns: The sorted observable.
3029
*/
3130
public func toSortedArray<T>(_ areInIncreasingOrder: @escaping (T, T) -> Bool)
32-
-> Observable<[T]> where E.Iterator.Element == T {
33-
return map { $0.sorted(by: areInIncreasingOrder) }
31+
-> Observable<[T]> where E.Element == T {
32+
return toArray().map { elements in
33+
elements.flatMap { element in
34+
element.sorted(by: areInIncreasingOrder)
35+
}
36+
}
3437
}
3538
}

0 commit comments

Comments
 (0)