Search code examples
kotlinreduxandroid-jetpack-composeandroid-jetpack-compose-list

Update State outside the composable function. (Jetpack compose)


I am trying to implement redux with Jetpack compose. The scenario looks like this:

I have a list view where I need to show data, in composable function.

    @Composable
    fun CreateListView(text: String) {
     val listdata = state { store.state }

        LazyColumn {
         //some listview code here
        }
    }

above, I want to use the data that I got from the redux store. but the store. The subscription method is standalone, and outside the composable. where, though I am able to update the state through new data, but the changes are not reflecting back to composable listview:

    // activity page outside composable
    private fun storeSubscription(){
        viewModel.storeSubscription = store.subscribe {

            when (store.state) {
                store.state = // list data from some source
            }
        }
    }

Is it possible to update the composable, like above, from outside the function, and without sending any parameter? Since the redux store is a global one, so it should work I think.


Solution

  • Try something like,

    @Composable
    fun <T> Store<T>.asState(): State<T> {
       val result = remember { mutableStateOf(store.state) }
       DisposableEffect {
           val unsubscribe = store.subscribe {
               result.value = store.state
           }
           onDispose { unsubscribe() }
       }
       return result
    }
    
    @Composable
    fun CreateListView(text: String) {
        val listdata by store.asState()
    
        LazyColumn {
         //some listview code here
        }
    }
    
    

    The exact code might differ as I don't know what redux implementation you are using.

    This creates an observable state object that will be updated whenever the lambda passed to subscribe is called. Also, it will automatically unsubscribe when CreateListView is no longer part of the composition.