Kotlin’s Supercharged Flow API — Combining and Merging Flows for Reactive Programming | by Nirbhay Pherwani | Aug, 2023
.combine
is a function provided by Kotlin’s Flow API. It allows us to combine two or more flows into a single flow, emitting values whenever any of the source flows emit a new value. This is useful for scenarios where you want to react to changes in multiple data sources and perform some operation on the combined data. Let’s look at a real-world example —
Consider a social media app where users can like, comment, and post. The function summarizedNotifications()
combines these activities into concise notifications. The sequence of results will print as follows —
- Likes and comments are combined for each corresponding post.
- The combined data is then merged with the posts, forming comprehensive notifications.
The use of the delay
function simulates real-time interactions for a more authentic user experience. For instance, users liking a post followed by a few comments followed by more reactions. This simulation adds a layer of realism to your app’s notification system.
Code
private fun summarizedNotifications() {
viewModelScope.launch {
val likesActivity: Flow<Like> = flowOf(*likesList.toTypedArray()).onEach {
delay(50)
}
val commentsActivity: Flow<Comment> = flowOf(*commentsList.toTypedArray()).onEach {
delay(200)
}
val postsActivity: Flow<Post> = flowOf(*postsList.toTypedArray()).onEach {
delay(100)
}
likesActivity.combine(commentsActivity) { like, comment ->
"${like.userName} reacted with ${like.reactionName} on ${like.postTitle}\n" +
"and ${comment.userName} commented ${comment.commentText} on ${comment.postTitle}"
}.combine(postsActivity) { activity, post ->
Log.i("Notification", "$activity .. Also ${post.userName} added a new post '${post.postTitle}'")
}.collect()
}
}
Example Data Input
You can find the data class and example data here.
Example Data Output
Rahul reacted with ❤ on Starry Night Photography
and Alice commented This is amazing! on Exploring the Cosmos .. Also Alice added a new post 'Exploring the Cosmos'
Rahul reacted with ❤ on Starry Night Photography
and Alice commented This is amazing! on Exploring the Cosmos .. Also Bob added a new post 'Starry Night Photography'
Grace reacted with ? on Astronomy Basics
and Alice commented This is amazing! on Exploring the Cosmos .. Also Bob added a new post 'Starry Night Photography'
Charlie reacted with ? on Starry Night Photography
and Alice commented This is amazing! on Exploring the Cosmos .. Also Bob added a new post 'Starry Night Photography'
Charlie reacted with ? on Starry Night Photography
and Alice commented This is amazing! on Exploring the Cosmos .. Also Charlie added a new post 'Astronomy 2 Basics'
...
...
...
Based on the delays provided in the code, likes will be emitted every 50 milliseconds, comments every 200 milliseconds, and posts every 100 milliseconds. The delay values influence the order in which the activities are emitted and combined.
As you can see, the activities are emitted in the order of the delays — likes, posts, and then comments. This is why Alice’s first like (refer input data) doesn’t appear first in the output. The delay of 50 milliseconds for likes causes the subsequent activities to be emitted and combined. As a result, the combination that striked (Rahul’s like) after her like at 100ms is the one that is actually printed.
Tip? — Do try
.combine()
with all three flows in the same function call to see the difference.
combine(likes, comments, posts) {likes, comments, posts ->
// log here
}.collect()
Tags In
Related Posts
Leave a Reply Cancel reply
Categories
- ! Без рубрики (1)
- ++PU (1)
- 1 (1)
- 1w (1)
- 1win Brazil (1)
- 1win India (1)
- 1WIN Official In Russia (1)
- 1win Turkiye (1)
- 1xbet egypt (1)
- 2ankarafayansustasi.net_may (1)
- ankarafayansustasi.netsiteai apr (1)
- Artificial intelligence (1)
- Arts & Entertainment, Photography (1)
- belugasitesi_mAY (1)
- BH_TOPsitesi apr (1)
- BHsitesy_may (2)
- Blog (3)
- Bookkeeping (14)
- Bootcamp de programação (2)
- Bootcamp de programación (2)
- BT_TOPsitesi apr (1)
- casino (5)
- casinom-hub (1)
- casinom-hub.comsitesi apr (3)
- colombian mail order brides (1)
- Cryptocurrency exchange (2)
- Dinamobet_next (1)
- Disease & Illness, Colon Cancer (1)
- Dumanbet (1)
- Dumanbet_next (1)
- Finance, Insurance (1)
- FinTech (5)
- Forex Trading (11)
- Galabet (1)
- Health & Fitness, Fitness Equipment (1)
- Hitbet (1)
- Home & Family, Crafts (1)
- Home & Family, Gardening (1)
- Internet Business, Audio-Video Streaming (1)
- Internet Business, Ecommerce (1)
- Internet Business, Email Marketing (1)
- Internet Business, Internet Marketing (1)
- IT Вакансії (1)
- IT Образование (5)
- IT Освіта (1)
- latin women dating (1)
- mail order bride (1)
- Mars bahis (2)
- Matadorbet (1)
- minimiri.comsitesi apr (3)
- Mobile App Development (771)
- Mostbet Russia (1)
- New Post (1)
- News (12)
- PB_TOPsitesi apr (1)
- PBsitesi_may (1)
- Pusulabet (1)
- redmirepool.bizsitesi apr (2)
- redmirepoolsitesi_may (1)
- Reference & Education, College (1)
- Reference & Education, Sociology (1)
- Rokusitesi apr (1)
- Sober living (6)
- Society, Divorce (1)
- Software development (7)
- Superbetin (1)
- Tempobet_next (1)
- thelongeststride.comsitesi apr (1)
- tipobet-turkiyesitesi apr (1)
- Ultrabet (1)
- Uncategorized (1)
- Игра (2)
- казино (1)
- Криптовалюты (1)
- Новости Криптовалют (1)
- Финтех (7)
- Форекс Брокеры (9)
- Форекс обучение (2)