From 361747841df61865aeab54f4b4263e56ef6162b7 Mon Sep 17 00:00:00 2001 From: chansooo Date: Wed, 2 Oct 2024 00:27:49 +0900 Subject: [PATCH] =?UTF-8?q?feat:=203=EC=B4=88=20throttle=EB=8F=99=EC=95=88?= =?UTF-8?q?=20=EB=93=A4=EC=96=B4=EC=98=A4=EB=8A=94=20count=20=ED=95=9C=20?= =?UTF-8?q?=EB=B2=88=EC=97=90=20=EB=B3=B4=EB=82=B4=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Sources/MemeDetailViewModel.swift | 52 +++++++++++++++---- 1 file changed, 42 insertions(+), 10 deletions(-) diff --git a/Projects/Features/MemeDetail/Sources/MemeDetailViewModel.swift b/Projects/Features/MemeDetail/Sources/MemeDetailViewModel.swift index 6248497..dc7342a 100644 --- a/Projects/Features/MemeDetail/Sources/MemeDetailViewModel.swift +++ b/Projects/Features/MemeDetail/Sources/MemeDetailViewModel.swift @@ -47,6 +47,9 @@ public final class MemeDetailViewModel: ViewModelType, ObservableObject { private let watchMemeUseCase: WatchMemeUseCase private let reactToMemeUseCase: ReactToMemeUseCase + private var reactionCount = 0 + private var reactionTask: Task? + // MARK: - Initializers public init( @@ -67,7 +70,8 @@ public final class MemeDetailViewModel: ViewModelType, ObservableObject { } deinit { - print("memeviewmodel deinit") + print("memeviewmodel deinit") + reactionTask?.cancel() } // MARK: - Methods @@ -110,19 +114,47 @@ public final class MemeDetailViewModel: ViewModelType, ObservableObject { } private extension MemeDetailViewModel { - + @MainActor - func postReaction() async { - do { - try await reactToMemeUseCase.execute(memeId: state.meme.id) + func postReaction() { + reactionCount += 1 self.state.meme.reaction += 1 self.state.meme.isReaction = true self.logMemeDetail(event: .reaction) - print("reaction success") - } catch { - // TODO: - 에러처리 - print("Failed to post reaction: \(error)") - } + + 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)") + } + } + } + } + + + @MainActor + func sendReactions() async { + let count = reactionCount + guard count > 0 else { + // 전송할 리액션이 없음 + return + } + reactionCount = 0 + do { + try await reactToMemeUseCase.execute(memeId: state.meme.id, count: count) + print("Reactions sent successfully with count: \(count)") + } catch { + print("Failed to send reactions: \(error)") + } } @MainActor