LiveData,当数据改变时可被观察到,同时具有生命感知能力,该能力是由于其内部类LifecycleBoundObserver继承了GenericLifecycleObserver->LifecycleEventObserver->LifecycleObserver。
关键代码:
observe(LifecycleOwner owner, Observer super T> observer) {
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
...
owner.getLifecycle().addObserver(wrapper);
}
当组件(如:Activity)生命周期状态改变时,会移除observer,所以也就不会发生内存泄漏。也不用手动处理生命周期。
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
removeObserver(mObserver);
return;
}
activeStateChanged(shouldBeActive());
}
使用:
LiveData通常放在ViewModel中,由ViewModel管理LiveData。
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class NameViewModel extends ViewModel {
MutableLiveData name;
public MutableLiveData getName() {
if (name == null) {
name = new MutableLiveData<>();
}
return name;
}
}
在Activity中,观察LiveData的改变
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
public class LiveDataActivity extends AppCompatActivity {
NameViewModel nameViewModel;
private TextView tvName;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_data);
nameViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory())
.get(NameViewModel.class);
nameViewModel.getName().observe(this, new Observer() {
@Override
public void onChanged(String s) {
//改变LiveData的值后,会被观察到,从而改变tvName的值
tvName.setText(s);
}
});
nameViewModel.getName().setValue("Android");
tvName = findViewById(R.id.tvName);
findViewById(R.id.btnChangeName).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//改变LiveData的值
nameViewModel.getName().setValue("Google");
}
});
}
}
当LiveData值改变时,TextView的内容也随之改变。