From Zero To Hero Series(Kotlin Sequences, Channels, Flows) — Part 1— Sequences
Kotlin language constains a container type which is called sequences. Sequences are very similar to lists. The difference between a list and sequence is that the sequences are lazily evaluated.
We can create sequences with different ways:
1 — From elements — By calling sequenceOf()
val numbersSequence = sequenceOf("four", "three", "two", "one")
We give elements as parameter to sequenceOf() function.
2- From iterable objects — By calling asSequence() function of an iterable object such as a List or Set.
val numbers = listOf("one", "two", "three", "four")
val numbersSequence = numbers.asSequence()
We can create a sequence by calling asSequence() function of an iterable object such as a List or Set.
3-From Chunks — sequence {}, yield, yieldAll()
val seqFromChunks = sequence {
yield(1)
yieldAll((2..5).toList())
yield(6)
}
Sequences execute lazily.
- What does it mean ? Can you show me with an example ?
- Yeap. I will show you it in example 1.
Sequence Example 1 :
Sequence Example 2 :
In this example, we use sequence{} to create a sequence. When we call
sequence.take(5).toList()
the codes inside the sequence{} start to work. When 5 elements are taken into sequence, the execution stops. Thus the next lines of codes are not executed. Analyse the following examples to understand.
Note that,
- sequences are not asynchoronous.
- sequences don’t support backpressure.
Benchmark Results between Sequences, RxJava and Flows
According to a benchmark results on scrabble game, Kotlin Flows are nearly 2 times faster than RxJava. Flows are a bit slower than Sequences. However Flows give you more possibilities, you can have asynchronous data producers, it supports backpressure. Since Flows support backpressure, it comes with a little overhead thus it’s a bit slower than sequences.
Difference between Sequence and Flow
Flows are asynchronous data stream.
A flow is an asynchronous version of a Sequence, a type of collection whose values are lazily produced. Just like a sequence, a flow produces each value on-demand whenever the value is needed, and flows can contain an infinite number of values.
In my article, i got help from the following links. Check these links for more information.
That’s all for now. See you in the 2nd part of this article for Channels.
Happy Sequence Coding.