Skip to content

Commit

Permalink
feat: 3초 throttle동안 들어오는 count 한 번에 보내도록 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
chansooo committed Oct 1, 2024
1 parent fea0d38 commit 3617478
Showing 1 changed file with 42 additions and 10 deletions.
52 changes: 42 additions & 10 deletions Projects/Features/MemeDetail/Sources/MemeDetailViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Void, Never>?

// MARK: - Initializers

public init(
Expand All @@ -67,7 +70,8 @@ public final class MemeDetailViewModel: ViewModelType, ObservableObject {
}

deinit {
print("memeviewmodel deinit")
print("memeviewmodel deinit")
reactionTask?.cancel()
}

// MARK: - Methods
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 3617478

Please sign in to comment.