avatarDawinder Singh Gill

Summary

The provided content discusses the differences between Cold Flow and Hot Flow in Kotlin's Flow API, explaining their characteristics, behaviors, and use cases.

Abstract

The article is part of a series on Kotlin's Flow API and serves as a guide for understanding Cold Flow and Hot Flow. Cold Flow emits data only when a collector is present, starting from the beginning for each new collector, which is suitable for scenarios where each collector needs the full data sequence. In contrast, Hot Flow emits data continuously, regardless of collectors, and can serve multiple collectors simultaneously, making it ideal for real-time data sharing among collectors. The author provides code examples to illustrate these concepts, demonstrating how each type of flow behaves with multiple collectors. The article concludes by summarizing the differences between Cold Flow and Hot Flow and teases the next part of the series, which will explore State Flow and Shared Flow. The author encourages readers to engage with the content, ask questions, and support the work through membership, donations, or following the author for more insights into Kotlin programming.

Opinions

  • The author suggests that newcomers to Kotlin Flow should start from the beginning of the series for a better understanding of the concepts.
  • The author expresses enthusiasm for Kotlin and the Flow API, indicating that mastering these concepts can improve one's programming skills.
  • The article conveys the opinion that choosing between Cold Flow and Hot Flow should be based on the specific needs of the application, such as whether data emission needs to be controlled or shared in real-time.
  • The author believes that reader support, through claps, shares, and donations, is valuable and encourages the creation of more educational content.
  • By inviting readers to follow for more content, the author implies that continuous learning and exploration of Kotlin's features are beneficial for developers.

Part 3: Exploring Kotlin’s Cold Flow and Hot Flow

This story is a part of the series I have written on Flow API in Kotlin. If you are new to Kotlin Flow then I’ll suggest you check this series from the beginning.

.

.

Introduction

In this story, we’ll dive into the fascinating world of Kotlin’s Cold Flow and Hot Flow. We’ll learn how they are different and what makes them special for reactive programming. Whether you love Kotlin or just want to improve your skills, this journey will help you understand when and how to use Cold Flow and Hot Flow effectively. Let’s begin our adventure and unlock the secrets of these powerful streams!

1. Cold Flow

Cold Flow is a type of Kotlin Flow that emits data only when there is a collector. It doesn't store any data and starts emitting values only when a collector subscribes to it. Each collector receives all the values from the beginning of the Flow independently, as if they have their individual flow. It's like a 1-to-1 mapping, where one Flow serves one collector, and each collector starts its Flow from the beginning.

fun getNumbersColdFlow() = flow {
    for (i in 1..5) {
        delay(1000)
        emit(i)
    }
}

fun main() = runBlocking {
    val numbersColdFlow = getNumbersColdFlow()

    println("1st Collector:")
    numbersColdFlow.collect { value ->
        println(value)
    }

    delay(2500)

    println("2nd Collector:")
    numbersColdFlow.collect { value ->
        println(value)
    }
}

// Output of the Cold Flow example:
1st Collector:
1
2
3
4
5
2nd Collector:
1
2
3
4
5

In this example, we have a Cold Flow called numbersColdFlow that emits integers 1 to 5 at a 1-second interval. When we collect values using two collectors (collect functions), both collectors start receiving the values from the beginning of the Flow.

As you can see, each collector gets the entire sequence of emitted values independently. This demonstrates the nature of Cold Flow, where each collector has its individual start point for data emission.

The key takeaway is that Cold Flow starts emitting data only when a collector subscribes, and each collector receives all the data from the beginning of the Flow.

2. Hot Flow

Hot Flow is a type of Kotlin Flow that emits data continuously, even when there is no collector. It can have multiple collectors, and each collector receives values from where they started collecting. It's like a 1-to-N mapping, where one Flow serves multiple collectors, and each collector receives data based on their individual subscription time.

fun getNumbersHotFlow(): MutableSharedFlow<Int> {
    val sharedFlow = MutableSharedFlow<Int>()
    runBlocking {
        launch {
            for (i in 1..5) {
                delay(1000)
                sharedFlow.emit(i)
            }
        }
    }
    return sharedFlow
}

fun main() = runBlocking {
    val numbersHotFlow = getNumbersHotFlow().asSharedFlow()

    println("1st Collector:")
    numbersHotFlow.collect { value ->
        println(value)
    }

    delay(2500)

    println("2nd Collector:")
    numbersHotFlow.collect { value ->
        println(value)
    }
}

// Output of the Hot Flow example:

1st Collector:
1
2
3
4
5
2nd Collector:
3
4
5

In the example, we have a Hot Flow called numbersHotFlow that emits integers 1 to 5 at a 1-second interval using a MutableSharedFlow. This Hot Flow continuously emits values even when there are no collectors.

When we collect values using two collectors (collect functions), the first collector starts receiving the values from the beginning, while the second collector starts receiving values after 2500 milliseconds.

As you can see, the first collector received all the emitted values, while the second collector only received the values emitted after 2500 milliseconds, as it started collecting later.

The key takeaway is that Hot Flow emits data continuously, and multiple collectors can subscribe to it at different times, receiving data from where they started collecting. This behavior makes Hot Flow suitable for scenarios where data needs to be shared among multiple collectors in real time.

Let’s summarize the differences between Cold Flow and Hot Flow in Kotlin:

Cold Flow:

  1. Data Emission: Emits data only when there is a collector. It starts emitting values only when a collector subscribes to it.
  2. Data Storage: This does not store data. It doesn’t retain previously emitted values.
  3. Collector Count: Can’t have multiple collectors. Each collector receives all the values from the beginning of the Flow independently.
  4. Behavior: Behaves like a 1-to-1 mapping, where one Flow serves one collector, and each collector starts its Flow from the beginning.
  5. Example: A simple Flow created using flow { ... } builder is a Cold Flow.

Hot Flow:

  1. Data Emission: Emits data continuously, even when there is no collector. It keeps emitting values regardless of whether there are any collectors.
  2. Data Storage: Can store data. It may retain previously emitted values, and collectors can receive those stored values when they subscribe.
  3. Collector Count: Can have multiple collectors. Each collector receives values from where they started collecting.
  4. Behavior: Behaves like a 1-to-N mapping, where one Flow serves multiple collectors, and each collector receives data based on their individual subscription time.
  5. Example: A Flow created using MutableSharedFlow is an example of Hot Flow.

Summary

  • Cold Flow emits data only when there is a collector, doesn’t store data, and each collector receives all the values from the beginning.
  • Hot Flow emits data continuously, can store data, and each collector receives data from where they started collecting.

Choose the appropriate type of Flow based on your application requirements. Cold Flow is beneficial when you want to control data emission and provide each collector with the complete data sequence. Hot Flow is suitable for scenarios where you need continuous data emission and shared data among multiple collectors.

What’s Next?

We’ll dive into State Flow and Shared Flow in software development. We’ll explore their differences, strengths, challenges, and how they impact coding projects.

Feel free to contact me ☎️ if you have any questions or need further clarification. Also don’t forget to give it multiple claps 👏 and share 🤝 it with others who might benefit from it. Your support is greatly appreciated and encourages me to continue sharing what I learn.

👉 Click here to become a Medium member and directly support my content and other writers content!

If you enjoyed this story and would like to show your support, I kindly invite you to consider making a donation 🎁. Your contribution, no matter the size, would mean the world to me. Thank you 🥰 for considering and for being a part of this journey!

Wanna show some LOVE 💝? 👉 Click Here

Lastly, follow 👥 Dawinder Singh Gill for more posts like this, where we delve into the world of coding, one line at a time. Happy coding!

Kotlin Flow
Cold Flow
Hot Flow
Reactive Programming
Best Practices
Recommended from ReadMedium