개발일기

Retrofit + Kotlin Flow로 실시간 데이터 처리

뱅우 2025. 9. 1. 09:41
반응형

Retrofit + Kotlin Flow로 실시간 데이터 처리

이전 글에서는 Retrofit + Coroutines를 이용해 네트워크 요청을 안전하게 처리하는 방법을 다뤘습니다. 이번 글에서는 한 단계 더 나아가, Kotlin Flow를 활용해 실시간 데이터 처리와 스트리밍/폴링을 구현하는 방법을 정리합니다.

1. 왜 Flow인가?

Coroutines의 suspend 함수는 단일 요청/응답에 적합합니다. 하지만, 주기적으로 갱신되는 데이터스트리밍 API를 다루려면 Flow를 사용하는 것이 훨씬 자연스럽습니다.

  • 주기적인 폴링 (예: 5초마다 서버 상태 확인)
  • 실시간 업데이트 (예: 채팅, 알림 스트림)
  • UI와 상태(StateFlow/Livedata) 연동

2. Flow로 주기적 API 호출하기

가장 기본적인 예시는 일정 주기로 API를 호출해 Flow로 내보내는 방식입니다.

fun pollUserStatus(api: ApiService, userId: String): Flow<NetworkResult<UserDto>> = flow {
    while (true) {
        val result = safeApiCall { api.getUser(userId) }
        emit(result)
        delay(5000) // 5초 주기 폴링
    }
}.flowOn(Dispatchers.IO)

ViewModel에서 collect하면 5초마다 최신 유저 상태가 업데이트됩니다.

ViewModel 사용 예

class UserViewModel(private val repo: UserRepository): ViewModel() {
    val userState: StateFlow<NetworkResult<UserDto>> =
        repo.observeUser("1")
            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), NetworkResult.Error(Exception("초기 상태")))
}

3. Retrofit + Flow 직접 연결하기

Retrofit 호출을 Flow로 감싸면, UI 단에서 더 직관적으로 쓸 수 있습니다.

fun <T> apiFlow(call: suspend () -> T): Flow<NetworkResult<T>> = flow {
    emit(NetworkResult.Loading) // optional
    emit(safeApiCall { call() })
}.flowOn(Dispatchers.IO)

이제 Repository에서 이렇게 작성할 수 있습니다:

class UserRepository(private val api: ApiService) {
    fun observeUser(id: String): Flow<NetworkResult<UserDto>> {
        return apiFlow { api.getUser(id) }
    }
}

4. Compose UI와 연동

Flow는 Jetpack Compose와 궁합이 좋습니다. collectAsState()를 활용하면 UI가 자동으로 갱신됩니다.

@Composable
fun UserScreen(viewModel: UserViewModel) {
    val userState by viewModel.userState.collectAsState()

    when (userState) {
        is NetworkResult.Success -> Text("User: ${(userState as NetworkResult.Success).data.name}")
        is NetworkResult.Error -> Text("Error 발생")
        NetworkResult.Loading -> CircularProgressIndicator()
    }
}

5. 정리

  • 단일 요청 → suspend 함수
  • 주기적/실시간 데이터 → Flow
  • UI (Compose)와 연동 시 자동 상태 업데이트

마무리: Flow는 네트워크 데이터 스트림을 간결하게 다룰 수 있는 도구입니다. 다음 글에서는 OkHttp Interceptor를 활용한 공통 에러 처리 & 로깅 전략을 다뤄보겠습니다.

반응형