Search code examples
androidkotlinandroid-jetpack-compose

Delegating mutable state to property in another object


I'm new to Jetpack Compose. Is there any way to delegate mutable state to property in another object ? I have classes like below:

class Contact(
    val name: String,
    val surname: String,
    private var _isFavourite: Boolean = false
) {

    var isFavourite
        get() = _isFavourite
        set(value) {
            // Some business work done here
            _isFavourite = value
        }
}

class ContactViewModel(contact: Contact) : ViewModel() {
    var isFavourite by mutableStateOf(contact.isFavourite)
}

I would like updates made to ContactViewModel's isFavourite property (which are done by ui) to cause update in Contact's isFavourite property (it may do some additional logic inside setter). The above does not work since I'm just passing value of contact.isFavourite as parameter to mutableStateOf.

I would maybe expect method like below, which takes property itself as parameter.

class ContactViewModel(contact: Contact) : ViewModel() {
    var isFavourite by mutableStateFromProperty(contact::isFavourite)
}

Is there some way to do this or maybe I just missed a method similar to described above ?


Solution

  • I don't know if it's what you want but you can use snapshotFlow to observe changes in MutableState, isFavourite, and collect and update the one in Contact class.

    init {
        viewModelScope.launch {
            snapshotFlow {
                isFavourite
            }
                .collect {
                    contact.isFavourite = it
                }
        }
    }