Skip to content

Instantly share code, notes, and snippets.

@tilltue
Created June 20, 2018 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tilltue/f8948f18b78a4f06bae0318ab5f1a723 to your computer and use it in GitHub Desktop.
Save tilltue/f8948f18b78a4f06bae0318ab5f1a723 to your computer and use it in GitHub Desktop.
currency firebase database model
protocol CurrencyFirebaseDB {
var ref: DatabaseReference { get }
func getExchangeRate() -> Observable<[CurrencyExchangeRate]>
}
extension CurrencyFirebaseDB {
var ref: DatabaseReference {
return Service.shared.container.resolve(DatabaseReference.self, name: Service.RegisterationName.firebaseCurrencyExchageRate.rawValue)!
}
var loadData: Observable<DataSnapshot> {
return Service.shared.container.resolve(Observable<DataSnapshot>.self, name: Service.RegisterationName.firebaseCurrencyExchageRate.rawValue)!
}
func deleteRef() {
self.ref.removeValue()
}
func getExchangeRate() -> Observable<[CurrencyExchangeRate]> {
let remoteApi = Api.getCurrencyExchangeRate(firebaseSaveBlock: { data in
log.debug("remote api")
if let dict = try? JSONDecoder().decode(ExchangeRate.self, from: data).convertDict() {
log.debug("save firebase database")
self.ref.setValue(dict, withCompletionBlock: { (_,_) in })
}
}).asObservable()
let firebaseApi = self.loadData.map{ snapshot in
log.debug("get firebase database")
var rates = [CurrencyExchangeRate]()
if let value = snapshot.value, let exchangeRate = try? FirebaseDecoder().decode(ExchangeRate.self, from: value) {
rates = exchangeRate.convertCurrencyExchangeRate()
CurrencyExchangeRateLocalApi.saveExchangeRate(rates: rates)
}
return rates
}.ifEmpty(switchTo: remoteApi)
return CurrencyExchangeRateLocalApi.getExchangeRate().do(onNext: { rates in
log.debug("getting local database")
if let time = rates.first?.updatedAt, Date(timeIntervalSince1970: time).moreThenOneDay() {
log.debug("local db: more then one day")
_ = firebaseApi.subscribe()
}
}).ifEmpty(switchTo: firebaseApi).observeOn(MainScheduler.instance)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment