[聚合文章] 浅析Android Architecture Components

软件架构 2017-11-22 15 阅读
image

前言

Architecture Components 是谷歌官方提出的 Android应用框架。这个新的框架库旨在帮助我们设计健壮、可测试和和维护的应用程序。现在 1.0的正式版已经发布了,下面让我们通过实际构建来了解一下。

构建

在项目的build.gradle中添加 Google Maven Repository

allprojects {    repositories {        google()        jcenter()        // Architecture Components        maven { url'https ://maven.google.com' }    }}

在模块build.gradle中添加相关依赖

如使用Lifecycle、LiveData、ViewModel,添加如下依赖。

    // Architecture components    implementation 'android.arch.lifecycle:runtime:1.0.3'    annotationProcessor "android.arch.lifecycle:compiler:1.0.0"    // LiveData ViewModel    implementation 'android.arch.lifecycle:extensions:1.0.0'

如使用 Room功能,添加如下依赖

    // room    implementation 'android.arch.persistence.room:runtime:1.0.0'    annotationProcessor "android.arch.persistence.room:compiler:1.0.0"    // testing Room migrations add    testImplementation 'android.arch.persistence.room:testing:1.0.0'

构建用户界面

现在有两个页面:商品列表和商品详情,列表界面由ProductListFragment和其对应的list_fragment组成
我们商品的数据模型如下:

public interface Product {    int getId();    String getName();    String getDescription();    int getPrice();}

我们用派生于AndroidViewModel(AndroidViewModel 继承于ViewModel)的ProductListViewModel来存储上面的数据,并向fragment提供数据

ViewModel

ViewModel是用来存储UI层的数据,以及管理对应的数据,当数据修改,马上刷新UI。

众所周知,Fragment和Activity本身需要处理很多用户的输入事件和操作系统打交道,如果还要花时间管理其数据的话,class文件就会变得异常大,这样的话如果进行单元测试或者更加多的功能的话,就会变得很臃肿和困难。

所以就有了MVC、MVP、MVVM等设计模式,将试图和数据分离,AAC中的ViewModel就是将数据从UI中分离出来,并且在页面重构的情况下,也能很好的管理数据

public class ProductListViewModel extends AndroidViewModel {    /**     *   MediatorLiveData can observe other LiveData objects and react on their emissions     */    private final MediatorLiveData<List<ProductEntity>> mObservableProducts;    public ProductListViewModel(@NonNull Application application) {        super(application);        mObservableProducts = new MediatorLiveData<>();        mObservableProducts.setValue(null);        LiveData<List<ProductEntity>> products = ((MyApplication)application).getRepository().getProducts();        mObservableProducts.addSource(products, mObservableProducts::setValue);    }    public LiveData<List<ProductEntity>> getProducts() {        return mObservableProducts;    }}

现在修改fragment 让其和viewmodel进行绑定,观察数据的变化并及时更新UI

    @Override    public void onActivityCreated(@Nullable Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        final ProductListViewModel viewModel = ViewModelProviders.of(this).get(ProductListViewModel.class);        subscribeUi(viewModel);    }

观察数据的变化并更新UI

    private void subscribeUi(ProductListViewModel viewModel) {        viewModel.getProducts().observe(this, new Observer<List<ProductEntity>>() {            @Override            public void onChanged(@Nullable List<ProductEntity> productEntities) {                if (productEntities!= null) {                    mBinding.setIsLoading(false);                    mProductAdapter.setProductList(productEntities);                } else  {                    mBinding.setIsLoading(true);                }            }        });    }

可能你会对其中的 很多东西不是很懂,不要着急,下面我会一一为其解答

LiveData

LiveData持有可悲观察的数据(也就是我们ProductListViewModel中的mObservableProducts),其中MediatorLiveData继承于LiveData。它使应用中的组件能在不于其存在明显依赖关系的前提下观察LiveData对象的改变。LiveData遵循应用组件的生命周期状态,并且能够阻止一下事情去阻止对象的内存泄漏。详情请阅LiveData

LiveDataViewModel的区别:

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。