Skip to content

Flow Context

Devrath edited this page Jan 19, 2024 · 2 revisions

Context-Image

Generating a flow with a certain context

  • Say you have a flow that is generating certain values and if you want to modify the context within the scope as below
  • It would result in an error java.lang.IllegalStateException: Flow invariant is violated

Code(That generates error)

    private fun generateIntegers() = flow {
        withContext(Dispatchers.Default){
            var currentValue = 0
            repeat(15){
                // Increment value
                currentValue ++
                // keep a delay
                delay(1000)
                // Emit a value
                println("Value on emission: $currentValue")
                emit(currentValue)
            }
        }
    }

    fun flowContextDemo() = viewModelScope.launch {
        generateIntegers().collect{
            println("Value on received: $it")
        }
    }

Code(Solution)

    private fun generateIntegers() = flow {
        var currentValue = 0
        repeat(15){
            // Increment value
            currentValue ++
            // keep a delay
            delay(1000)
            // Emit a value
            println("Value on emission: $currentValue")
            emit(currentValue)
        }
    }.flowOn(Dispatchers.IO)

    fun flowContextDemo() = viewModelScope.launch {
        generateIntegers().collect{
            println("Value on received: $it")
        }
    }
Clone this wiki locally