LiveData update on object field change

后端 未结 5 1695
渐次进展
渐次进展 2020-11-27 12:49

I\'m using Android MVVM architecture with LiveData. I have an object like this

public class User {
    private String firstName;
    private String lastName;         


        
5条回答
  •  醉话见心
    2020-11-27 13:18

    If you are using Kotlin and LiveData, I can offer you 2 ways - with and without extension fucntion:

    Without extension function

    liveData.value = liveData.value?.also { it ->
        // Modify your object here. Data will be auto-updated
        it.name = "Ed Khalturin"
        it.happyNumber = 42
    }
    

    Same, but with extension

    // Extension. CopyPaste it anywhere in your project
    fun  MutableLiveData.mutation(actions: (MutableLiveData) -> Unit) {
        actions(this)
        this.value = this.value
    }
    
    // Usage
    liveData.mutation {
        it.value?.name = "Ed Khalturin"
        it.value?.innerClass?.city= "Moscow" // it works with inner class too
    }
    

提交回复
热议问题