Skip to content

Commit

Permalink
Live activity update throttling added
Browse files Browse the repository at this point in the history
  • Loading branch information
XITRIX committed Jul 28, 2024
1 parent 79d92ff commit 2aeb5b2
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions iTorrent/Services/LiveActivityService/LiveActivityService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ actor LiveActivityService {
}
}

private static let throttleDuration: Int = 5
private var throttleMap: [String: Date] = [:]
private let disposeBag = DisposeBag()
@Injected private var torrentService: TorrentService
}
Expand All @@ -42,14 +44,10 @@ private extension LiveActivityService {
if let snapshot = updateModel.handle?.snapshot,
snapshot.friendlyState.shouldShowLiveActivity
{
if #available(iOS 16.2, *) {
await activity.update(.init(state: snapshot.toLiveActivityState, staleDate: .now + 10))
} else {
await activity.update(using: snapshot.toLiveActivityState)
}
await update(activity, with: snapshot.toLiveActivityState)
return
} else {
await activity.end(dismissalPolicy: .immediate)
await end(activity)
return
}
}
Expand All @@ -63,12 +61,34 @@ private extension LiveActivityService {
}
}

@available(iOS 16.1, *)
func update(_ activity: Activity<ProgressWidgetAttributes>, with state: ProgressWidgetAttributes.ContentState) async {
if let date = throttleMap[activity.attributes.hash],
Int(Date.now.timeIntervalSince(date)) <= Self.throttleDuration
{ return }

if #available(iOS 16.2, *) {
await activity.update(.init(state: state, staleDate: .now + 10))
} else {
await activity.update(using: state)
}

throttleMap[activity.attributes.hash] = .now
}

@available(iOS 16.1, *)
func end(_ activity: Activity<ProgressWidgetAttributes>) async {
await activity.end(dismissalPolicy: .immediate)
throttleMap[activity.attributes.hash] = nil
}

func showLiveActivity(with snapshot: TorrentHandle.Snapshot) {
if #available(iOS 16.1, *) {
let attributes = ProgressWidgetAttributes(hash: snapshot.infoHashes.best.hex)

do {
_ = try Activity<ProgressWidgetAttributes>.request(attributes: attributes, contentState: snapshot.toLiveActivityState, pushType: .none)
throttleMap[attributes.hash] = .now
} catch {
print(error.localizedDescription)
}
Expand Down

0 comments on commit 2aeb5b2

Please sign in to comment.