Is there a better pattern for managing state in km...
# multiplatform
b
Is there a better pattern for managing state in kmp? I've got a project with koin and room so I'm trying to make sure composables accept state in the arguments and the viewmodels can still take advantage of DI and avoiding having to pass arguments all over the place. But having issues updating lists within the state. Posting an example inside this messages thread:
Copy code
data class ListState(
    val query: String = "", 
    val items: List<String> = emptyList(), 
    val editItem: String = ""
)

@Dao
interface ItemDao {
    @Query("select * from item where name like :name order by name")
    fun findAllByName(name: String): Flow<String>
    @Query("select * from item order by name")
    fun findAll(): Flow<String>
}

class ListViewModel(
    state: ListState,
    private val dao: ItemDao,
): ViewModel() {
    private val _state = MutableStateFlow(state)
    
    val state = combine(
        _state,
        loadItems(state.query)
    ) { s, l ->
        s.copy(items = l)
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(3000), state)
    
    fun loadItems(query: String? = null) = when {
        query.isNullOrEmpty() -> dao.findAll()
        else -> dao.findAllByName(query)
    }
    
    fun handleEvent(event: EventType) {
        when(event) {
            is EventType.Search -> TODO()
        }
    }
}
a
Slack has a state framework for composable, its quite nice. https://github.com/slackhq/circuit I have used it as inspiration in my projects.
👀 1