iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎉

Relearning Flow: Part 1

に公開

A series of notes on things I found interesting while looking through the link below to properly review Flow.
*Not sure if this will actually become a series.
https://kotlinlang.org/docs/flow.html#transform-operator

transform operator

viewLifecycleOwner.lifecycleScope.launch {
    (1..3).asFlow().transform { request ->
        emit("Making request $request")
        delay(500)
        emit(request)
    }.collect { response ->
        if (response is String) {
            println(response)
        } else {
            println("Not String $response")
        }
    }
}

According to the official documentation, it can be used to emit a string before calling a heavy process and then emit the result once it's received.
It seems useful even when you want to intentionally show a loading animation, as you can just use delay.
It also mentions it can be used to implement transformations that cannot be done with map or filter, which makes it a very versatile tool.

Terminal flow

val sum = (1..5).asFlow()
    .map { it * it } // squares of numbers from 1 to 5
    .reduce { a, b ->
        println("A:$a B:$b")
        a + b
    } // sum them (terminal operator)
println(sum)
2021-08-03 20:47:39.316 11857-11857/sobaya.example.allflow I/System.out: A:1 B:4
2021-08-03 20:47:39.317 11857-11857/sobaya.example.allflow I/System.out: A:5 B:9
2021-08-03 20:47:39.317 11857-11857/sobaya.example.allflow I/System.out: A:14 B:16
2021-08-03 20:47:39.317 11857-11857/sobaya.example.allflow I/System.out: A:30 B:25
2021-08-03 20:47:39.317 11857-11857/sobaya.example.allflow I/System.out: 55

So reduce receives the previous value and the newly passed value.

val sum = (1..5).asFlow()
    .map { it * it } // squares of numbers from 1 to 5
    .fold(1) { a, b ->
        println("A:$a B:$b")
        a + b
    } // sum them (terminal operator)
    println(sum)
}
2021-08-03 21:02:02.152 13054-13054/sobaya.example.allflow I/System.out: A:1 B:1
2021-08-03 21:02:02.152 13054-13054/sobaya.example.allflow I/System.out: A:2 B:4
2021-08-03 21:02:02.152 13054-13054/sobaya.example.allflow I/System.out: A:6 B:9
2021-08-03 21:02:02.152 13054-13054/sobaya.example.allflow I/System.out: A:15 B:16
2021-08-03 21:02:02.152 13054-13054/sobaya.example.allflow I/System.out: A:31 B:25
2021-08-03 21:02:02.152 13054-13054/sobaya.example.allflow I/System.out: 56

fold works similarly to reduce but allows you to specify an initial value.

That's it for the first day.

Discussion