在返回之前获取 Observable 数组的计数
Get count of Observable array before returning it
在我的 ViewModel 文件中,我有一个在应用地图后创建的可观察数组。现在在 return 之前我想检查它是否有任何内容。如果那里什么都没有,我想 return 它而不应用地图。以下是我的代码:
func retrieveDeals(location: CLLocation?) -> Observable<[SaleItem]> {
let specials = nearestFlightSpecials.retrieveNearestFlightSpecials(userLocation: location)
let happyHourDeals = specials.map {
[=10=].filter { [=10=].isHappyHour }
}
return happyHourDeals
}
在我 return happyHourDeals 之前,我想检查它是否包含任何元素。上面的数组已在视图中订阅,但我不想在那里应用上面的逻辑。我想将它保留在 ViewModel 中。
我怀疑你想做的是过滤掉空输出:
func retrieveDeals(location: CLLocation?) -> Observable<[SaleItem]> {
let specials = nearestFlightSpecials.retrieveNearestFlightSpecials(userLocation: location)
let happyHourDeals = specials.map {
[=10=].filter { [=10=].isHappyHour }
}
.filter { ![=10=].isEmpty } // this is the line you need.
return happyHourDeals
}
术语在这里很重要。 Observables 不“包含”值。 Observables 没有 return 值,它们会发出事件。
您的 happyHourDeals
仍将被 return 编辑,但使用 filter
行,它将不再发出空数组。这意味着如果 specials.map { [=13=].filter { [=13=].isHappyHour } }
发出一个空数组,则订阅值 returned 的任何内容都不会更新。
在我的 ViewModel 文件中,我有一个在应用地图后创建的可观察数组。现在在 return 之前我想检查它是否有任何内容。如果那里什么都没有,我想 return 它而不应用地图。以下是我的代码:
func retrieveDeals(location: CLLocation?) -> Observable<[SaleItem]> {
let specials = nearestFlightSpecials.retrieveNearestFlightSpecials(userLocation: location)
let happyHourDeals = specials.map {
[=10=].filter { [=10=].isHappyHour }
}
return happyHourDeals
}
在我 return happyHourDeals 之前,我想检查它是否包含任何元素。上面的数组已在视图中订阅,但我不想在那里应用上面的逻辑。我想将它保留在 ViewModel 中。
我怀疑你想做的是过滤掉空输出:
func retrieveDeals(location: CLLocation?) -> Observable<[SaleItem]> {
let specials = nearestFlightSpecials.retrieveNearestFlightSpecials(userLocation: location)
let happyHourDeals = specials.map {
[=10=].filter { [=10=].isHappyHour }
}
.filter { ![=10=].isEmpty } // this is the line you need.
return happyHourDeals
}
术语在这里很重要。 Observables 不“包含”值。 Observables 没有 return 值,它们会发出事件。
您的 happyHourDeals
仍将被 return 编辑,但使用 filter
行,它将不再发出空数组。这意味着如果 specials.map { [=13=].filter { [=13=].isHappyHour } }
发出一个空数组,则订阅值 returned 的任何内容都不会更新。