androidkotlinandroid-jetpack-composekotlin-multiplatform

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!


Solution

  • 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.