0
0
Kotlinprogramming~10 mins

Flow context preservation in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a simple flow emitting numbers 1 to 3.

Kotlin
val numbersFlow = flow {
    for (i in 1..3) {
        emit([1])
    }
}
Drag options to blanks, or click blank then click option'
Ai
B3
Cflow
Dcollect
Attempts:
3 left
💡 Hint
Common Mistakes
Using a fixed number like 3 instead of the loop variable.
Trying to emit the flow itself instead of a value.
2fill in blank
medium

Complete the code to collect values from the flow and print them.

Kotlin
runBlocking {
    numbersFlow.[1] { value ->
        println(value)
    }
}
Drag options to blanks, or click blank then click option'
Aemit
BflowOn
Claunch
Dcollect
Attempts:
3 left
💡 Hint
Common Mistakes
Using emit instead of collect.
Trying to launch the flow instead of collecting.
3fill in blank
hard

Fix the error in the code to switch the flow context to Dispatchers.IO.

Kotlin
val ioFlow = numbersFlow.[1](Dispatchers.IO)
Drag options to blanks, or click blank then click option'
AflowOn
Bcollect
Claunch
Demit
Attempts:
3 left
💡 Hint
Common Mistakes
Using collect or emit which do not change context.
Trying to launch the flow instead of switching context.
4fill in blank
hard

Fill both blanks to create a flow that emits squares of numbers only if they are even.

Kotlin
val evenSquares = flow {
    for (x in 1..5) {
        if (x [1] 2 == 0) {
            emit(x [2] x)
        }
    }
}
Drag options to blanks, or click blank then click option'
A%
B*
C+
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or subtraction instead of multiplication for square.
Using wrong operator for checking even numbers.
5fill in blank
hard

Fill all three blanks to create a flow that emits uppercase strings only if their length is greater than 3.

Kotlin
val words = listOf("cat", "lion", "tiger", "dog")
val filteredFlow = flow {
    for (word in words) {
        if (word.[1] > 3) {
            emit(word.[2]())
        }
    }
}.[3](Dispatchers.Default)
Drag options to blanks, or click blank then click option'
Alength
BtoUpperCase
CflowOn
DtoLowerCase
Attempts:
3 left
💡 Hint
Common Mistakes
Using toLowerCase() instead of toUpperCase().
Forgetting to switch the flow context with flowOn.
Using parentheses incorrectly on properties.