Complete the code to create a simple Flow that emits numbers from 1 to 3.
val numbersFlow = flow {
for (i in 1..[1]) {
emit(i)
}
}The flow emits numbers from 1 to 3, so the upper limit in the range should be 3.
Complete the code to collect values from the Flow and print them.
runBlocking {
numbersFlow.[1] { value ->
println(value)
}
}To receive and process emitted values from a Flow, you use the collect function.
Fix the error in the code to make the Flow emit values on the IO dispatcher.
val ioFlow = numbersFlow.[1](Dispatchers.IO)The flowOn operator changes the dispatcher where the upstream flow runs.
Fill both blanks to create a Flow that emits squares of numbers greater than 2.
val squaresFlow = flow {
for (num in 1..5) {
if (num [1] 2) {
emit(num [2] num)
}
}
}The condition checks if the number is greater than 2, and then emits its square by multiplying the number by itself.
Fill all three blanks to create a Flow that emits uppercase strings longer than 3 characters.
val words = listOf("cat", "lion", "tiger", "dog") val filteredFlow = flow { for (word in words) { if (word.length [1] 3) { emit(word.[2]().[3]()) } } }
The condition filters words longer than 3 characters. The uppercase() function converts the string to uppercase. The toUpperCase() is an alternative method call to ensure uppercase conversion.