var spendingObserver: TransactionObserver?
init() {
....
let observation = ValueObservation.tracking(value: { db in
try Outcome.fetchAll(db, sql: "select cost from outcome where date >= ?", arguments: [startOf15DaysAgo])
})
self.spendingObserver =
try! observation.start(in: databasePool, onChange: { outcomes in
self.todayTotal =
outcomes.filter { (outcome) -> Bool in
outcome.date >= startOfToday
}.map({ (outcome) -> Double in
outcome.cost
}).reduce(0, +)
self.yesterdayTotal =
outcomes.filter({ (outcome) -> Bool in
outcome.date < startOfToday && outcome.date >= (startOfToday - 1.days)
}).map({ (outcome) -> Double in
outcome.cost
}).reduce(0, +)
})
...
}
use the viewmodel inside SwiftUI View.
@ObservedObject var viewModel = UserSpendingViewModel()
...
SpendingSection(title: "Today", total: viewModel.todayTotal)
# it shows the data correctly
But when I try to insert a new record to database. It fails ACCESS_BAD_ADDRESS
, debug view shows as follows, looks like it needs a strong reference?