Skip to content

Instantly share code, notes, and snippets.

@alouanemed
Created May 3, 2020 12:18
Show Gist options
  • Save alouanemed/0c11ec4cc01dcb2d756fdde411181b7c to your computer and use it in GitHub Desktop.
Save alouanemed/0c11ec4cc01dcb2d756fdde411181b7c to your computer and use it in GitHub Desktop.
let onUnit = BehaviorRelay(value: "")
let onTotal = BehaviorRelay(value: "")
let onPriceUpdated = BehaviorRelay<ProductPriceEntity?>(value: nil)
let onQuantity = BehaviorRelay(value: 1)
var prices: [ProductPriceEntity] = []
Observable.combineLatest(onUnit, onQuantity).flatMapLatest{[weak self] (unit, qty) -> Observable<Void> in
guard let self = self else { return Observable.just(()) }
let price = self.unitPrices.value[unit]?.filter { price in
let min = price.minCount ?? 1
let max = price.maxCount ?? 1
if max < min {
return min...max ~= qty
}else{
return false
}
}.first
//Calculate Item Total
var total = 0
var currency = ""
if let priceData = price, qty >= priceData.minCount ?? 1 && qty <= priceData.maxCount ?? 1{
let cents = priceData.price?.cents ?? 0
currency = priceData.price?.currencyIso ?? ""
total = cents * qty
self.pricePerUnit.accept("\(StringUtils.format(price: cents, currencyCode: currency)) /\(priceData.unit ?? "")")
self.priceBreakDown.accept("\(priceData.minCount ?? 1) - \(priceData.maxCount ?? 1) \(priceData.unit ?? ""): \(StringUtils.format(price: priceData.price?.cents ?? 0, currencyCode: priceData.price?.currencyIso ?? "")) / \(priceData.unit ?? "")")
}else{
self.pricePerUnit.accept(R.string.localizable.ordersRequestTitle.key.localized())
total = 0
}
if total == 0 {
self.pricePerUnit.accept(R.string.localizable.ordersRequestTitle.key.localized())
self.priceBreakDown.accept("-")
self.onTotal.accept(R.string.localizable.orderEditPriceTBC.key.localized())
}else{
self.onTotal.accept(StringUtils.format(price: total, currencyCode: currency))
}
if let data = price {
self.onPriceUpdated.accept(data)
}
return Observable.just(())
}.subscribe(onNext: {[weak self](_) in
}).disposed(by: rx.disposeBag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment