Skip to content

Commit

Permalink
Merge branch 'feature/recommend-iOS18' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
jongnan committed Oct 3, 2024
2 parents bed48e0 + 94a2195 commit b746404
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 30 deletions.
37 changes: 23 additions & 14 deletions Projects/Core/PPACUtil/Sources/Throttler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,40 @@
import Foundation

public class Throttler {
private var workItem: DispatchWorkItem?
private var lastExecution: Date?
private let queue: DispatchQueue
private let interval: TimeInterval
private var task: Task<Void, Never>?

public init(seconds: TimeInterval, queue: DispatchQueue = DispatchQueue.main) {
public init(seconds: TimeInterval) {
self.interval = seconds
self.queue = queue
}

public func throttle(action: @escaping () -> Void) {
@MainActor
public func throttle(action: @escaping () async -> Void) {
// 기존의 예약된 작업이 있으면 취소
workItem?.cancel()
task?.cancel()

// 새로운 작업 생성
workItem = DispatchWorkItem { [weak self] in
self?.lastExecution = Date()
action()
task = Task { [weak self] in
guard let self else { return }

do {
// 지정된 시간만큼 대기

try await Task.sleep(nanoseconds: UInt64(self.interval * 1_000_000_000))

await action()
} catch {
if Task.isCancelled {
// 태스크가 취소되었으므로 아무 작업도 하지 않음
return
} else {
print("Task error: \(error)")
}
}
}

// 인터벌 후에 작업을 실행하도록 예약 (즉시 실행하지 않음)
queue.asyncAfter(deadline: .now() + interval, execute: workItem!)
}

public func cancel() {
workItem?.cancel()
task?.cancel()
}
}
21 changes: 5 additions & 16 deletions Projects/Features/MemeDetail/Sources/MemeDetailViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ public final class MemeDetailViewModel: ViewModelType, ObservableObject {

private var reactionCount = 0
private var reactionTask: Task<Void, Never>?

private let trotller = Throttler(seconds: 3)



Expand Down Expand Up @@ -135,22 +137,9 @@ private extension MemeDetailViewModel {
self.state.meme.reaction += 1
self.state.meme.isReaction = true
self.logMemeDetail(event: .reaction)

reactionTask?.cancel()

reactionTask = Task { [weak self] in
guard let self = self else { return }
do {
try await Task.sleep(nanoseconds: 3 * 1_000_000_000)
await self.sendReactions()
} catch {
if Task.isCancelled {
// 태스크가 취소되었으므로 아무 작업도 하지 않음
return
} else {
print("Task error: \(error)")
}
}

trotller.throttle {
await self.sendReactions()
}
}

Expand Down

0 comments on commit b746404

Please sign in to comment.