Complete the code to create a simple flow emitting numbers 1 to 3.
val numbersFlow = flow {
for (i in 1..3) {
emit([1])
}
}The emit function sends each value from the flow. Here, i is the current number in the loop.
Complete the code to collect values from the flow and print them.
runBlocking {
numbersFlow.[1] { value ->
println(value)
}
}emit instead of collect.The collect function gathers the emitted values from the flow and lets you process them.
Fix the error in the code to switch the flow context to Dispatchers.IO.
val ioFlow = numbersFlow.[1](Dispatchers.IO)collect or emit which do not change context.The flowOn operator changes the context where the flow runs, here to Dispatchers.IO.
Fill both blanks to create a flow that emits squares of numbers only if they are even.
val evenSquares = flow {
for (x in 1..5) {
if (x [1] 2 == 0) {
emit(x [2] x)
}
}
}The modulo operator % checks if a number is even. The multiplication operator * calculates the square.
Fill all three blanks to create a flow that emits uppercase strings only if their length is greater than 3.
val words = listOf("cat", "lion", "tiger", "dog") val filteredFlow = flow { for (word in words) { if (word.[1] > 3) { emit(word.[2]()) } } }.[3](Dispatchers.Default)
toLowerCase() instead of toUpperCase().flowOn.length gets the string length, toUpperCase() converts to uppercase, and flowOn changes the flow context.