Search code examples
kotlinkotlin-coroutineskotlin-flow

Why Statements after kotlin's MutableStateFlow collect methods are unreachable?


var hotFlow = MutableStateFlow("John")
lifecycleScope.launch{
            hotFlow.collect {
                println("Value Of Data $it")
            }
            println("Hello UnReachable")
        }

I'm expecting when code initialization takes place or when I update the value of MutableStateFlow, println() should print above written statements, but it is not printed and also lint compiler shows that particular println() statement is unreachable, why is that so?..


Solution

  • Because collect on a SharedFlow never returns. The Kotlin compiler is smart about that, and sees the Nothing return type. So it knows that call can't complete normally, and all statements below it are unreachable.

    See the docs for details.