공부/Android

[Android] flow 사용시 주의(하나의 launched effect에서 여러개 collect를 하면안된다!)

데자와 맛있다 2023. 11. 2. 14:30

프로젝트를 하던 도중....

한 launched effect에서 여러개의 flow를 collect 하려고했다

이런식으로

근데 viewModel에서 값이 바뀌는것까지 다 확인을 했는데 저 color changed가 로그가 안찍혔다...

그래서

이렇게 바꾸니깐 color changed가 호출됨

헐;

그래서 찾아보니깐

https://co-zi.medium.com/stateflow-%EB%A5%BC-collect-%ED%95%A0%EB%95%8C%EC%9D%98-%EC%A3%BC%EC%9D%98%ED%95%A0%EC%A0%90-d1826818b773

 

StateFlow 를 collect 할때의 주의할점

TLDR; StateFlow.collect 는 루프를 사용하기 때문에 다음 코드 진행을 막는다.

co-zi.medium.com

StateFlow.collect 는 루프를 사용하기 때문에 다음 코드 진행을 막는다.

라고 적혀있다

ㄷㄷ;

그래서 밑에거가 실행이 안된거임

이거를 해보면 hi?? 가출력이안됨

https://stackoverflow.com/questions/76016624/can-two-collect-be-used-with-the-same-stateflow

 

Can two collect be used with the same StateFlow?

I am trying to understand the use of flow in Kotlin and I was trying different codes, in particular I was with this method: val stateFlow = MutableStateFlow(0) private fun stateFlowWithContinueCo...

stackoverflow.com

collect를 여러개 하고싶다면 각기 다른 코루틴 내에서 해야된단다(무한 루프이므로)

해결방안은 다음에 이어서계속..