Jetpack Compose how to recompose when internal state changes

I’m quite new to Jetpack Compose and what I am running into is a conceptual issue that I am seeking a “This is how you would typically do that” on. Could also be that my approach to the problem is not done in a way that suits Compose.

I have a NotificationService in my app (a singleton where different components can add notifications) that has a composable function to render the current notifications in separate windows.
This is a simplified version of it

object NotificationService {
    private val notifications = mutableListOf<NotificationContainer>()

    @Composable
    fun renderNotifications() {
        // cleanup old notifications
        notifications.removeAll { it.showUntil.isBefore(OffsetDateTime.now()) }

        var index = 0
        notifications.forEach {
            Notification(it.message, index)
            index++
        }
    }

    fun notificationCount(): Int {
        return notifications.size
    }

    fun addNotification(message: String) {
        notifications.add(NotificationContainer(message, OffsetDateTime.now().plusSeconds(5)))
    }
}

data class NotificationContainer(val message: String, val showUntil: OffsetDateTime)

I now call the render function in the main part of my app like so:

fun main() = application {
    // dependencies
    val notificationService = NotificationService

    notificationService.renderNotifications()

    OtherComposable() { ... }
}

OtherComposable also has an reference to NotificationService and add notifications on button clicks as a test. The render function is only called once in the beginning. I understand why this happens, there’s no inputs changing on the render, etc, – Compose has no reason to recompose app here, since only the internal state NotificationService changed. How are components handled that only internally know when they should be recomposed? I also tried exposing the notification count, so the parent could know when the count changes and recompose then, but I didn’t know how I would need to bind/propagate the count to the parent. How is a case like this generally handled when you need to tell your parent “Please redraw me, my state changed in a relevant way”?

Cheers and thanks!

2

The usual way to go is to keep your data in Flows (which are observable containers for data) and in your composables you convert the Flows into Compose State objects.

Your NotificationService would look like this:

object NotificationService {
    private val notifications = MutableStateFlow(listOf<NotificationContainer>())

    @Composable
    fun renderNotifications() {
        // cleanup old notifications
        notifications.update { list ->
            list.filterNot { it.showUntil.isBefore(OffsetDateTime.now()) }
        }

        val list by notifications.collectAsState()

        list.forEachIndexed { index, notification ->
            Notification(notification.message, index)
        }
    }

    fun notificationCount(): Int {
        return notifications.value.size
    }

    fun addNotification(message: String) {
        notifications.update {
            it + NotificationContainer(message, OffsetDateTime.now().plusSeconds(5))
        }
    }
}

Although a MutableStateFlow has a value property that can be used to change its value you should use the update function whenever the new value depends on the old value. That is necessary because flows are asynchronous data structures and therefore one update could interfere with another when done concurrently. update is guaranteed to change the value atomically preventing any synchronization issues.

For the flow to properly identify changes to the value the value should be immutable. That’s why a List is used here, not a MutableList. The code in the update lambda therefore always returns a new list, not a modified list.

Your composable then simply needs to convert the flow to a State object with collectAsState(). That State will now automatically update when the flow updates, and a changed State results in a recomposition, so your UI is also updated.

To simplify things the State object returned by collectAsState() is unwrapped by using Kotlin delegates (the by keyword), so list is of type List<NotificationContainer>.

I also simplified the forEach loop with a dedicated index variable to the built-in forEachIndexed. That is unrelated to the current problem, though.


That said, your current approach mixing data sources with composables (your NotificationService object) should usually be avoided. Instead you want your composables to be top-level functions and all data they need should be provided as parameters. The collection of flows should be hoisted out as far as possible, you should only pass the list to renderNotifications.

Since you mentioned Android and view models in the comments, in such a case the MutableStateFlow should be held by the view model and exposed as a read-only StateFlow with .asStateFlow(). The composable that retrieves the view model should directly collect the flow using collectAsStateWithLifecycle() from the gradle dependency androidx.lifecycle:lifecycle-runtime-compose.

Don’t pass view model instances or flows around in your composables, the parameters should only be simple immutable (data) objects.


One last thing: The “cleanup old notifications” part should be placed somewhere else, outside of your composables. As it is now it may be executed repeatedly and unnecessarily, i.e. on each recomposition. That doesn’t seem to be the correct condition for the cleanup.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật