ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • coroutine - 하나의 scope 안에서 collect를 하지 않는 이유
    Android 2023. 3. 30. 18:45
     private fun collectFlow() {
            viewLifecycleOwner.lifecycleScope.launch {
                viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                    viewModel.books.collectLatest {
                        if (it.isNotEmpty()) {
                            pplAdapter.submitList(it)
                        }
                    }
             
                }
            }
    
            viewLifecycleOwner.lifecycleScope.launch {
                viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                    viewModel.video.collectLatest {
                        if (it.isNotEmpty()) {
                            vidAdapter.submitList(it)
                        }
                    }
                }
            }
        }

    에서 하나의 scope 안에서 collect를 하지 않는 이유

    viewModel.books와 viewModel.video는 서로 다른 Flow 객체를 반환한다.
    이러한 Flow 객체들은 비동기로 데이터를 전달하며, collectLatest를 사용하여 수신 대기 중인 최신 데이터를 수집한다.

    따라서, 두 개의 서로 다른 Flow를 별도의 launch 블록으로 처리해야 한다.
    두 Flow를 하나의 launch 블록으로 처리하면, 하나의 Flow가 차단되거나 지연될 때 다른 Flow의 처리도 함께 지연될 가능성이 있다.
    ( 실제로 하나의 블록에서 처리할때는 뒤의 블록이 실행이 되지 않았음! )
    따라서, 개별적인 launch 블록을 사용하여 두 Flow를 병렬로 처리하면 더 효율적이고 안정적으로 데이터를 수집할 수 있다!

    'Android' 카테고리의 다른 글

    StartActivityForResult  (0) 2023.07.04
    Service  (0) 2023.03.25
    Coroutine  (0) 2023.03.24
    context  (0) 2023.03.24
    Intent + broadcast  (0) 2023.03.24

    댓글

Designed by Tistory.