Android: Listening for variable changes

后端 未结 2 585
情书的邮戳
情书的邮戳 2020-12-08 13:30

I\'ve been searching for a KISS example of how to do this, and while they all seem (and I\'ve gone through them ALL!) simple enough, I still cannot get my head around the co

2条回答
  •  一生所求
    2020-12-08 14:14

    There is a much easier solution now. Just wrap your variable in a LiveData Specifically MutableLiveData.

    Java Version

    MutableLiveData listen = new MutableLiveData<>();
    
    listen.setValue("Changed value"); //Initilize with a value
    
    listen.observe(context, new Observer  > () {
        @Override
        public void onChanged(String changedValue) {
            //Do something with the changed value
        }
    });
    

    Kotlin Version

    val listen : MutableLiveData =  MutableLiveData<>()
    
    listen.setValue("Changed value") //Initilize with a value
    
    listen.observe(context, Observer {
    
        //Do something with the changed value -> it
    
    })
    

提交回复
热议问题