我有一个相同类的Observable of Objects数组= Observable <[MyClass]>。 MyClass包含一个Observable属性sortAttribute = Observable。 我想根据可观察的sort属性对数组进行排序。
class MyClass {
let title:String
let sortAttribute:Observable<Int>
init(withTitle title:String, andSortValue sortValue: Int) {
self.title = title
self.sortAttribute = Observable.just(sortValue)
}
}
let arrayToSort:Observable<[MyClass]> = Observable.just([
MyClass(withTitle: "A", andSortValue: 4),
MyClass(withTitle: "B", andSortValue: 2),
MyClass(withTitle: "C", andSortValue: 42),
MyClass(withTitle: "D", andSortValue: 1337),
MyClass(withTitle: "E", andSortValue: 24)
])
arrayToSort
.subscribe(onNext: { ar in
for element in ar {
print(element.title)
}
})
实际结果:
A //4
B //2
C //42
D //1337
E //24
预期结果:
B //2
A //4
E //24
C //42
D //1337
答案 0 :(得分:2)
arrayToSort
.flatMap { classes in
Observable.combineLatest(
classes.map { elem in
elem.sortAttribute.map { (elem, $0) }
}
)
}
.map {
$0.sorted(by: { a, b in a.1 < b.1 }).map { $0.0.title }
}
.subscribe(onNext: {
print($0)
})
答案 1 :(得分:0)
尝试一下:
arrayToSort
.subscribe(onNext: { ar in
let sortedAr = ar.sorted(by: { $0.title < $1.title })
for element in sortedAr {
print(element.title)
}
})
更新: 设置您的排序属性NOT Observable ... Just Int
class MyClass {
let title:String
let sortAttribute: Int
init(withTitle title:String, andSortValue sortValue: Int) {
self.title = title
self.sortAttribute = sortValue
}
}
然后:
arrayToSort
.subscribe(onNext: { ar in
let sortedAr = ar.sorted(by: { $0.sortAttribute < $1.sortAttribute })
for element in sortedAr {
print(element.title)
}
})
如果将其保留为Observable,则必须订阅每个sortAttribute提取其Int,然后以某种方式对其进行排序,这对于简单的排序来说浪费了处理能力...