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 range should be 1..3.
Complete the code to collect and print each value emitted by the Flow.
numbersFlow.[1] { value ->
println(value)
}To receive and handle emitted values from a Flow, use the collect function.
Fix the error in the code to emit strings instead of integers.
val stringFlow = flow {
for (i in 1..3) {
emit([1])
}
}i emits integers, not strings.To emit strings, convert the integer i to string using toString().
Fill both blanks to create a Flow that emits only even numbers from 1 to 5.
val evenFlow = flow {
for (num in 1..5) {
if (num [1] 2 == 0) {
emit(num[2])
}
}
}The modulo operator % checks if a number is even by testing remainder 0. The emit function just emits the number as is, so no operator needed after num.
Fill all three blanks to create a Flow that emits squares of numbers greater than 2 from 1 to 4.
val squaresFlow = flow {
for (x in 1..4) {
if (x [1] 2) {
emit(x [2] x)
}
}
}
squaresFlow.collect { value ->
println(value [3] 0)
}We check if x is greater than 2 using >. Then emit the square by multiplying x by x. Finally, print whether each value is greater than 0.