Skip to content

Commit

Permalink
[IDLE-468] 웹소켓 연결 실패시 2의 배수만큼 기다렸다가 연결을 재시도 하도록 변경 및 최대 대기시간은 10초
Browse files Browse the repository at this point in the history
  • Loading branch information
tgyuuAn committed Feb 10, 2025
1 parent a3c20c0 commit 302c4f1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class ChattingRepositoryImpl @Inject constructor(
webSocketDataSource.disconnectWebSocket()

override fun subscribeChatMessage(): Flow<ChatMessage> =
webSocketDataSource.getChatMessageFlow()
webSocketDataSource.chatMessageFlow
.filterNotNull()
.map { it.toVO() }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,29 @@ package com.idle.network.source.websocket
import com.idle.network.BuildConfig
import com.idle.network.di.WebSocketOkHttpClient
import com.idle.network.model.chatting.ChatMessageResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.pow

@Singleton
class WebSocketDataSource @Inject constructor(
@WebSocketOkHttpClient private val client: OkHttpClient,
private val chatMessageListener: ChatMessageListener,
) {
val chatMessageFlow: StateFlow<ChatMessageResponse?> = chatMessageListener.chatMessageFlow

private lateinit var chatMessageWebSocket: WebSocket
private var connectionAttempts = 0

fun connectWebSocket(): Result<Unit> {
return try {
suspend fun connectWebSocket(): Result<Unit> = withContext(Dispatchers.IO) {
try {
val chatMessageRequest: Request = Request.Builder()
.url(BuildConfig.CARE_WEBSOCKET_URL)
.build()
Expand All @@ -29,6 +35,8 @@ class WebSocketDataSource @Inject constructor(
Result.success(Unit)
} catch (e: Exception) {
if (connectionAttempts < MAX_RETRY_ATTEMPTS) {
val waitTime = minOf(calculateBackoffTime(connectionAttempts), MAX_WAIT_TIME)
delay(waitTime)
connectionAttempts++
connectWebSocket()
} else {
Expand All @@ -48,9 +56,11 @@ class WebSocketDataSource @Inject constructor(
}
}

fun getChatMessageFlow(): StateFlow<ChatMessageResponse?> = chatMessageListener.chatMessageFlow
private fun calculateBackoffTime(attempt: Int): Long =
(2.0.pow(attempt) * 1000).toLong()

companion object {
private const val MAX_RETRY_ATTEMPTS = 5
private const val MAX_WAIT_TIME = 10_000L // 10 seconds
}
}

0 comments on commit 302c4f1

Please sign in to comment.