Jetpack架构之LiveData

2021-01-17  本文已影响0人  NengLee

LiveData是一个可以被观察的数据持有类,它具有感知 Activity,Fragmen或是Servers等组件的生命周期。而且LiveData和ViewMode是经常搭配在一起使用的。

特点

LiveData使用

implementation "androidx.lifecycle:lifecycle-livedata:2.2.0"
package com.example.livedata;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class MyLiveData extends ViewModel {


    //MutableLiveData是LiveData的子类,
    private MutableLiveData<String> mutableLiveData;

    //获取 MutableLiveData对象,
    public MutableLiveData<String> getMutableLiveData() {
        if (mutableLiveData == null)
            mutableLiveData = new MutableLiveData<>();

        return mutableLiveData;
    }
}
package com.example.livedata;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


    private MyLiveData myLiveData;
    private String TAG = getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myLiveData = new MyLiveData();

        //观察者
        Observer<String> observer = s -> {
            Log.e(TAG, "onChanged: " + s);
            ((TextView) findViewById(R.id.tex_tv)).setText(s);
        };

        //注册观察者 带当前生命周期感知
        myLiveData.getMutableLiveData().observe(this, observer);
        //注册观察者,无
        //myLiveData.getMutableLiveData().observeForever(observer);
    }


    public void onButton(View view) {
        //发送一个Message事件
        myLiveData.getMutableLiveData().setValue("Hello LiveData");
    }
}

当点击But事件便会回调Observe的观察者的void onChanged(T t); 回调方法。

总线Bus管理LiveData

package com.example.livedata.Bus;

import androidx.lifecycle.MutableLiveData;

import java.util.HashMap;
import java.util.Map;

public class LiveDataBus<T> {

    //存放观察者
    private static Map<String, MutableLiveData<Object>> busMap;

    private static LiveDataBus liveDataBus = new LiveDataBus();

    public synchronized static <T> LiveDataBus<T> getLiveDataBus() {
        if (busMap == null)
            busMap = new HashMap<>();
        return liveDataBus;
    }
    
    //注册观察者
    public synchronized <T> MutableLiveData<T> with(String ket, Class<T> tClass) {
        //查询
        if (!busMap.containsKey(ket)) {
            //创建一个MutableLiveData
            busMap.put(ket, new MutableLiveData<>());
        }
        //返回当期需要的MutableLiveData
        return (MutableLiveData<T>) busMap.get(ket);
    }
}

上一篇 下一篇

猜你喜欢

热点阅读