Complete the code to create a flow that emits numbers from 1 to 3.
val numberFlow = flow {
emit([1])
emit(2)
emit(3)
}The emit function sends values to the flow. Here, the first emitted value should be 1.
Complete the code to collect and print each value from the flow.
runBlocking {
numberFlow.[1] { value ->
println(value)
}
}The collect function is used to receive and process each value emitted by the flow.
Fix the error in the flow builder by completing the code to emit squares of numbers from 1 to 3.
val squareFlow = flow {
for (i in 1..3) {
emit(i [1] i)
}
}The multiplication operator * is used to calculate the square of each number.
Fill both blanks to create a flow that emits even numbers from 1 to 6.
val evenFlow = flow {
for (num in 1..6) {
if (num [1] 2 == 0) {
emit(num[2]0)
}
}
}The modulo operator % checks if a number is even by seeing if the remainder when divided by 2 is zero. The plus operator + is used here to emit the number as is (no change).
Fill all three blanks to create a flow that emits uppercase strings from a list and collects them.
val words = listOf("apple", "banana", "cherry") val upperFlow = flow { for (word in words) { emit(word[1]) } } runBlocking { upperFlow.[2] { value -> println(value[3]) } }
.uppercase() converts strings to uppercase in Kotlin 1.5+. The collect function gathers emitted values. .toUpperCase() is a valid method to print the string in uppercase (older style).