Jetpack -LiveData

一、简介

LiveData:LiveData是一种持有可被观察数据的类。LiveData有生命周期感知能力的,可以在activities, fragments, 或者 services生命周期是活跃状态(STARTED和RESUMED)时会通知数据变化,更新这些组件。
特点:

  • 感知生命周期,实时获取数据变化;组件销毁后,会清除数据,避免内存泄漏。
  • 旋转屏幕,组件被系统回收后可以恢复数据。
  • 共享数据:使用单例模式扩展LiveData对象以包装系统服务,以便可以在应用程序中共享它们。 LiveData对象连接到系统服务一次,然后任何需要该资源的观察者都可以只观看LiveData对象。

二、使用

2.1 基本使用

使用MutableLiveData,通常在onCreate中使用执行

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

        MutableLiveData mutableLiveData  = new MutableLiveData<>();
        mutableLiveData.observe(this, new Observer() {//1
            @Override
            public void onChanged(@Nullable final String s) {
                Log.d(TAG, "onChanged:"+s);
            }
        });
        mutableLiveData.postValue("LiveData");
    }

同步:接收端数据回调与发送端同一个线程。
userLiveData.setValue(user);
异步:接收端在主线程回调数据。
userLiveData.postValue(user);

2.2 自定义LiveData

数据共享,保持LiveData为单例,在不同的地方调用,达到数据共享
重要方法:

//处于活跃状态
void onActive ()
//有活跃状态变为不活跃状态
void onInactive ()

实现监听网络,网络发生变化时通过setValue()通知

public class NetworkLiveData extends LiveData {

    private final Context mContext;
    static NetworkLiveData mNetworkLiveData;
    private NetworkReceiver mNetworkReceiver;
    private final IntentFilter mIntentFilter;

    private static final String TAG = "NetworkLiveData";

    public NetworkLiveData(Context context) {
        mContext = context.getApplicationContext();
        mNetworkReceiver = new NetworkReceiver();
        mIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    }

    public static NetworkLiveData getInstance(Context context) {
        if (mNetworkLiveData == null) {
            mNetworkLiveData = new NetworkLiveData(context);
        }
        return mNetworkLiveData;
    }

    @Override
    protected void onActive() {
        super.onActive();
        Log.d(TAG, "onActive:");
        mContext.registerReceiver(mNetworkReceiver, mIntentFilter);
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        Log.d(TAG, "onInactive: ");
        mContext.unregisterReceiver(mNetworkReceiver);
    }

    private static class NetworkReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager manager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
            getInstance(context).setValue(activeNetwork);

        }
    }
}
NetworkLiveData.getInstance(this).observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable NetworkInfo networkInfo) {
                Log.d(TAG, "onChanged: networkInfo=" +networkInfo);
            }
        });

三、修改合并LiveData

3.1、修改LiveData数据

修改LiveData数据是在LiveData对象分发给观察者之前可以使用Transformations.map()和Transformations.switchMap()对其中存储的值进行更改

3.1.1、Transformations.map

Transformations.map():在LiveData对象分发给观察者之前对其中存储的值进行更改

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

        MutableLiveData mutableLiveData = new MutableLiveData<>();
        mutableLiveData.observe(this, new Observer() {//1
            @Override
            public void onChanged(@Nullable final String s) {
                Log.i(TAG, "onChanged: " + s);
            }
        });
        Transformations.map(mutableLiveData, new Function() {
            @Override
            public String apply(String input) {
                return input + "Transformations.map";
            }
        }).observe(this, new Observer() {
            @Override
            public void onChanged(String s) {
                Log.i(TAG, "onChanged: " + s);
            }
        });


输出:
2019-10-31 23:06:48.525 21243-21243/com.xxxx.xxxx I/MainActivity: onChanged: LiveData:
2019-10-31 23:06:48.526 21243-21243/com.xxxx.xxxx I/MainActivity: onChanged: LiveData:Transformations.map

3.1.2、Transformations.switchMap

转化为新的LiveData,有点类似于RxJava的Map方法

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

        final MutableLiveData mutableLiveData = new MutableLiveData<>();
        MutableLiveData booleanMutableLiveData = new MutableLiveData<>();

        Transformations.switchMap(booleanMutableLiveData, new Function>() {
            @Override
            public LiveData apply(Boolean input) {
                return mutableLiveData;
            }
        }).observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable final String s) {
                Log.d(TAG, "onChanged:" + s);
            }
        });
        booleanMutableLiveData.postValue(false);
        mutableLiveData.postValue("mutableLiveData");
    }


输出:
2019-10-31 23:14:15.570 22036-22036/com.xxxx.xxxx D/MainActivity: onChanged:mutableLiveData

3.1、合并LiveData数据-MediatorLiveData

MediatorLiveData可以将多个LiveData数据源集合起来,可以达到一个组件监听多个LiveData数据变化的目的。

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MutableLiveData mutableLiveData1  = new MutableLiveData<>();
        MutableLiveData mutableLiveData2  = new MutableLiveData<>();
        MediatorLiveData liveDataMerger = new MediatorLiveData();
        liveDataMerger.addSource(mutableLiveData1, new Observer() {
            @Override
            public void onChanged(Object o) {
                Log.i(TAG, "onChanged mutableLiveData1: "+Objects.requireNonNull(o).toString());
            }
        });
        liveDataMerger.addSource(mutableLiveData2, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                Log.i(TAG, "onChanged mutableLiveData2: "+Objects.requireNonNull(o).toString());
            }
        });
        liveDataMerger.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                Log.d(TAG, "onChanged:"+ Objects.requireNonNull(o).toString());
            }
        });
        mutableLiveData1.postValue("MediatorLiveData");
        mutableLiveData2.postValue("MediatorLiveData");
    }

输出:
2019-10-31 23:23:56.704 23685-23685/? I/MainActivity: onChanged mutableLiveData1: MediatorLiveData
2019-10-31 23:23:56.705 23685-23685/? I/MainActivity: onChanged mutableLiveData2: MediatorLiveData

你可能感兴趣的:(Jetpack -LiveData)