-
안드로이드 Coroutine Flow - 3 (StateFlow) 코드안드로이드 학습/Android 기술면접 대비 2024. 12. 2. 14:37
ViewModel
class CoroutineStateFlowViewModel : ViewModel() { // StateFlow private val _coroutineData = MutableStateFlow(CoroutineUiState.success("")) val coroutineData: StateFlow<CoroutineUiState<String>> = _coroutineData.asStateFlow() // ShareFlow private val _sharedFlow = MutableSharedFlow<String>( replay = 1, extraBufferCapacity = 1 ) val sharedFlow: SharedFlow<String> = _sharedFlow .shareIn( scope = viewModelScope, // viewModelScope로 생명주기 관리 started = SharingStarted.WhileSubscribed(1000), // 구독자가 없을 때 5초 후 정지 replay = 1 // 최근 값 1개 재생 ) // StateIn private val _stateInFlow:StateFlow<String> = makeFlowData().stateIn( scope = viewModelScope, // CoroutineScope started = SharingStarted.WhileSubscribed(1000), // Flow 시작 시점 설정 initialValue = "Initial State" // 초기 값 ) val stateInFlow: StateFlow<String> = _stateInFlow fun loadData() { viewModelScope.launch { try { _coroutineData.value = CoroutineUiState.loading() val data = makeFlowData() // 실제 데이터 가져오기 data.collect { result -> _coroutineData.value = CoroutineUiState.success(result) } } catch (e: Exception) { _coroutineData.value = CoroutineUiState.error(e.message.toString()) // 에러 상태 } } } fun emitSharedFlowData() { viewModelScope.launch { _sharedFlow.emit("emit ShardFlowData") } } private fun makeFlowData(): Flow<String> = flow { delay(1000) // 서버에서 데이터를 가져온다는 시간을 가상으로 emit("Get Data From Server Successly") } }
Fragment 구독
// StateFlow 구독 lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { launch { coroutineStateFlowViewModel.coroutineData.collect { result -> when (result.status) { CoroutineStatus.LOADING -> showLoadingBar() CoroutineStatus.SUCCESS -> setTextView(result.data) CoroutineStatus.ERROR -> showErrorMsg(result.message) } } } launch { coroutineStateFlowViewModel.sharedFlow.collect { result -> setTextView2(result) } } launch { coroutineStateFlowViewModel.stateInFlow.collect { result -> setTextView3(result) } } } }
'안드로이드 학습 > Android 기술면접 대비' 카테고리의 다른 글
안드로이드 아키텍처 (MVC) (0) 2024.12.09 안드로이드 앱 테스트 기본 - 2 (UI Test예제 포함) (0) 2024.12.07 안드로이드 Coroutine Flow - 3 (StateFlow) (0) 2024.11.28 안드로이드 Coroutine Flow - 2 (Flow 사용) (0) 2024.11.28 안드로이드 Coroutine Flow - 1 (Flow란?) (0) 2024.11.27