---
title: "Discussion on \"Leveraging fold operator in Kotlin flow to optimize Room DB upserts\" | Hashnode"
description: "Discussion on \"Leveraging fold operator in Kotlin flow to optimize Room DB upserts\". Hey everyone, today we will look into an interesting topic to optimize room DB upserts using fold in Kotlin flow.\nThe case?\nWe are working on a chat application where we fetch a list of chats in pages from the network and upsert it into DB as it is a..."
url: "https://hashnode.com/posts/leveraging-fold-operator-in-kotlin-flow-to-optimize-room-db-upserts/655c44afe10e32209234a4f1"
---

[Feed](https://hashnode.com/feed) /

Discussion

# [Leveraging fold operator in Kotlin flow to optimize Room DB upserts](https://tusharpingale.hashnode.dev/leveraging-fold-operator-in-kotlin-flow-to-optimize-room-db-upserts?utm_source=hashnode&utm_medium=feed)

Hey everyone, today we will look into an interesting topic to optimize room DB upserts using fold in Kotlin flow. The case? We are working on a chat application where we fetch a list of chats in pages from the network and upsert it into DB as it is a...

Nov 21, 2023 · 6 min read · tusharpingale.hashnode.dev  
Updated Nov 22, 2023  
Read the article

-   [#kotlin](https://hashnode.com/tag/kotlin)
-   [#kotlin-coroutines](https://hashnode.com/tag/kotlin-coroutines)
-   [#kotlin-flow](https://hashnode.com/tag/kotlin-flow)
-   [#android](https://hashnode.com/tag/android)
-   [#room-database](https://hashnode.com/tag/room-database)

## Written by

[Tushar Pingale](https://hashnode.com/@tusharpingale04)

@tusharpingale04

  
[View profile](https://hashnode.com/@tusharpingale04)

Make dreams happen

Technical Lead Android @Paytm

## Responses 2

Markdown supported · ⌘↵ to post

[Ilya](https://hashnode.com/@Snowmaze)

[Jul 9, 2025](https://hashnode.com/posts/leveraging-fold-operator-in-kotlin-flow-to-optimize-room-db-upserts/655c44afe10e32209234a4f1/comment/686eae2a3c049ed70a8ca99d)

Why wouldn't you just use subList? db.chatDao().insertChats(list.subList(0, 45))

if (list.size > 45) list.subList(45, list.size).chunked(150).forEach { db.chatDao().insertChats(it) }

[Tushar Pingale](https://hashnode.com/@tusharpingale04)

[Nov 30, 2025](https://hashnode.com/posts/leveraging-fold-operator-in-kotlin-flow-to-optimize-room-db-upserts/655c44afe10e32209234a4f1/comment/686eae2a3c049ed70a8ca99d#reply-692c37f4d5a60d94966e73b9)

This is because we are unaware of the list size. The list is populated based on paginated response.

[Siddhesh Redkar](https://hashnode.com/@Siddh)

[Nov 21, 2023](https://hashnode.com/posts/leveraging-fold-operator-in-kotlin-flow-to-optimize-room-db-upserts/655c44afe10e32209234a4f1/comment/655c64882a6c065f3be51a64)

🙌🏻 Great job
