Skip to content

Commit 4e51ca8

Browse files
committed
Observe opened product and reload stats upon changes
1 parent dd2f59c commit 4e51ca8

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

WooCommerce/Classes/ViewRelated/Dashboard/TopPerformers/TopPerformersDashboardViewModel.swift

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ final class TopPerformersDashboardViewModel: ObservableObject {
3030
private let analytics: Analytics
3131

3232
private var resultsController: ResultsController<StorageTopEarnerStats>?
33+
private var entityListener: EntityListener<Product>?
3334

3435
private var currentDate: Date {
3536
Date()
@@ -83,6 +84,7 @@ final class TopPerformersDashboardViewModel: ObservableObject {
8384
self.usageTracksEventEmitter = usageTracksEventEmitter
8485

8586
observeSyncingCompletion()
87+
observeSelectedItem()
8688

8789
Task { @MainActor in
8890
self.timeRange = await loadLastTimeRange() ?? .today
@@ -215,6 +217,42 @@ private extension TopPerformersDashboardViewModel {
215217
.store(in: &subscriptions)
216218
}
217219

220+
func observeSelectedItem() {
221+
$selectedItem
222+
.scan((nil, nil)) { (previous: (current: TopEarnerStatsItem?,
223+
previous: TopEarnerStatsItem?),
224+
newValue: TopEarnerStatsItem?) in
225+
return (current: newValue, previous: previous.current)
226+
}
227+
.sink { [weak self] (newItem, oldItem) in
228+
guard let newItem, oldItem == nil else {
229+
self?.entityListener = nil
230+
return
231+
}
232+
self?.observeOpenedProductIfPossible(id: newItem.productID)
233+
}
234+
.store(in: &subscriptions)
235+
}
236+
237+
func observeOpenedProductIfPossible(id: Int64) {
238+
guard var product = storageManager.viewStorage.loadProduct(siteID: siteID, productID: id)?.toReadOnly() else {
239+
return
240+
}
241+
let entityListener = EntityListener(storageManager: ServiceLocator.storageManager, readOnlyEntity: product)
242+
entityListener.onUpsert = { [weak self] updatedProduct in
243+
// reload stats if there are changes to product
244+
guard updatedProduct.name != product.name ||
245+
updatedProduct.imageURL != product.imageURL else {
246+
return
247+
}
248+
product = updatedProduct
249+
Task {
250+
await self?.reloadDataIfNeeded(forceRefresh: true)
251+
}
252+
}
253+
self.entityListener = entityListener
254+
}
255+
218256
@MainActor
219257
func loadLastTimeRange() async -> StatsTimeRangeV4? {
220258
await withCheckedContinuation { continuation in

0 commit comments

Comments
 (0)