Architecture Components

1.Why "Architecture" Components?

2.what does architecture components include?

{

  Room //a robust SQL object mapping library

  ViewModel //provide data for UI components and survive configuration changes

  LiveData  //monitor changes,database observer and also lifecycle observer

  Lifecycle //lifecycle aware component

}

3.how to use Room component?

3.1 define a Plain Old Java Object,or a POJO.

then mark this POJO with the @Entity annotation and create an ID market with the @PrimaryKey annotation.

@Entity
public class Trail{
    public @PrimaryKey String id;
    public String name;
    public double kilometers;
    public int difficulty;
}

3.2 Now for each POJO,you need to define a DAO,or a Database.

The annotated methods represent the SQLite,commands that you need to interact with your POJO‘s data.

Room also verifies your SQLite at compile time.So if you spell something a little bit wrong int the database,it will throw a helpful error.

TrailDao.java

@Dao
public interface TrailDao{
    //Create,read,update,delete examples
    @Insert(onConflict=IGNORE)
    void insertTrail(Trail trail)

     @Query("SELECT * FROM Trail")
    public  List<Trail> findAllTrails();

    @Update(onConflict = REPLACE)
    void updateTrail(Trail trail)

    @Query("DELETE FROM Trail")
    void deleteAll();
}

LiveData is an observable data holder.It notifies obervers when data changes so that you can  update the UI,or,for simple cases,you can use the MutableLiveData class.

MutableLiveData<String> dayOfWeek = new MutableLiveData<>();
dayOfWeek.observe(this,data->{
        mTextView.setText(dayOfWeek.getValue()+"Thursday is a good day for a hike.");});
dayOfWeek.setValue("Friday");

If you update the value of the MutableLiveData with a call to set value,it could then trigger and update in your UI.What‘s even more powerful though,is that Room is built to support LiveData.

To use them together,you just modify your DAO class.

TrailDao.java

@Dao
public interface TrailDao{
    //Create,read,update,delete examples
    @Insert(onConflict=IGNORE)
    void insertTrail(Trail trail)

     @Query("SELECT * FROM Trail")
    public LiveData<List<Trail>> findAllTrails();

    @Update(onConflict = REPLACE)
    void updateTrail(Trail trail)

    @Query("DELETE FROM Trail")
    void deleteAll();
}

Then you could write code like this to update your UI.

trailsLiveData.observe(this,trails->{
    //Update UI,in this case a RecyclerView
    mTrailsRecyclerAdapter.replaceItems(trails);
    mTrailsRecyclerAdapter.notifyDataSetChanged();
});

  The end result is that if your Room database updates,it changes the data in your LiveData object,which automatically triggers UI updates

 3.3 LiveData is an obervable data holder.It notifies observers when data changes so that you can update the UI.It is also lifecycle aware.

Lifecycle Aware Component?

LiveData knows when your activity is on screen,off screen,or destroyed,so that is doesn‘t send database updates to a non-active UI.

There are two interfaces for this:

LifecycleOwners are objects with lifecycles,like Acitivies and Fragments.

LifecycleObservers observe LifecycleOwners and are notified of lifecycle changes.

Here‘s a quick peek at the simplified:code for LiveData,which is also a Lifecycle Observer.

LiveData.java

abstract public class LiveData<T> implements LifecycleObserver{
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void startup(){...}

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void cleanup(){...}
}

Observing Flow:

As a side note to all you Android library designers out there,you can use this exact same lifecycle obervation code to call setup and tear down functions automatically.

Your Library

 MyLibraryClass implements LifecycleObserver{
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void startup(){...}

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void cleanup(){...}
}

4.Avoid a lot of needlessly re-executed code.associated with the UI in a ViewModel instead.

ViewModel:View models are objects that provide data for UI components and survive configuration changes.

TrailListViewModel.java

public class TrailListViewModel extends AndroidViewModel{
    private AppDatabase mDatabase;

    private LiveData<<List<Trail>>> trails;

    public TrailListViewModel(Application application){
        super(application);
        mDatabase=AppDatabase.getDb(getApplication());
        trails=mDatabase.trailModel().findAllTrails();
    }
}

Then,when you are creating your activity or fragment,you can get a reference to the ViewModel

and use it.

 RecommendedTrailsActivity.java
//In onCreate
trailListViewModel=ViewModelProviders.of(this)
.get(TrailViewModel.class);

//Code to set up the RecyclerView omitted
trailListViewModel.getTrails().observe(this,trails->{
   mTrailsRecyclerAdapter.replaceItems(trails);
   mTrailsRecyclerAdapter.notifyDataSetChanged();
);

 The first time you get a ViewModel,it is generated for your activity.When you request a ViewModel again,your activity receives the original ViewModel,no more useless database calls.

5. In Summary

Altogether,they make up a set of architecture components for writing modular,testable,and robust Android apps.

时间: 2024-10-10 02:52:19

Architecture Components的相关文章

App 组件化/模块化之路——Android 框架组件(Android Architecture Components)使用指南

面对越来越复杂的 App 需求,Google 官方发布了Android 框架组件库(Android Architecture Components ).为开发者更好的开发 App 提供了非常好的样本.这个框架里的组件是配合 Android 组件生命周期的,所以它能够很好的规避组件生命周期管理的问题.今天我们就来看看这个库的使用. 通用的框架准则 官方建议在架构 App 的时候遵循以下两个准则: 关注分离 其中早期开发 App 最常见的做法是在 Activity 或者 Fragment 中写了大量

安卓构架组件&mdash;&mdash;概述 Android Architecture Components

谷歌官文文档地址:https://developer.android.google.cn/topic/libraries/architecture 安卓构架组建是库的集合:帮助你设计健壮的.易测试的.可维护的应用.使用类作为入口管理UI组建的生命周期和处理数据持久化. Android architecture components are a collection of libraries that help you design robust, testable, and maintainab

Building Maintainable Software-java篇之Keep Architecture Components Balanced

Building encapsulation boundaries is a crucial skill in software architecture. -George H. Fairbanks in Just Enough Architecture Guideline: ? Balance the number and relative size of top-level components in your code. ? Do this by organizing source cod

2.0.Architecture components架构组件

参考 https://developer.android.com/topic/libraries/architecture/ Architecture架构组件 架构组件是Jeppack中的一组支持库,主要用于帮助开发者构建一个健壮的架构. 很早就接触这个,但一直用的云里雾里的,年前和最近一段时间把官方文档和源码全都过了一遍,算是理解更深入了, 之后的几篇相关文章我不只是把用法列出来,会把一些源码分析做一些说明. Data Binding Declaratively bind observable

【Android】Architecture Components最佳实践--Lifecycles

UI controllers (activities and fragments) 中代码越少越好,不应该自己去请求数据,而是用ViewModel来更新数据,并且监听LiveData来更新UI UI controllers 中的UI写成数据驱动的,也就是UI controller需要做的只有当数据变化时更新view,或者当用户有输入行为时给ViewModel反馈 把数据逻辑放在ViewModel中,ViewModel存在的目的是将UI controller 与应用内其他的一切分离.ViewMod

Flask architecture

论文The Flask Security Architecture: System Support for Diverse Security Policies 介绍了Flask architecture 以下节选自该论文 Figure 1: The Flask architecture. Components which enforce security policy decisions are referred to as object managers. Components which p

Android Architecture Components--项目实战

转载请注明出处,谢谢! 上个月Google Android Architecture Components 1.0稳定版发布,抽工作间隙写了个demo,仅供参考 Github地址:https://github.com/AllenWen/android-iWeather 1.亮点 一是生命周期管理---Lifecycles,各类组件的引用与周期绑定,从而有效避免内存泄漏: 二是LiveData,数据流中的主角,作用类似于Rx的Observer; 三是推出全新数据库ORM框架---Room,当然也是

安卓构架组件&mdash;&mdash;向项目添加组件(Adding Components to your Project)

在开始之前,建议阅读 应用架构指南. Before getting started, we recommend reading the Architecture Components Guide to App Architecture. The guide has some useful principles that apply to all Android apps, and shows how to use the Architecture Components together. 原文地

Apache Kafka: Next Generation Distributed Messaging System---reference

Introduction Apache Kafka is a distributed publish-subscribe messaging system. It was originally developed at LinkedIn Corporation and later on became a part of Apache project. Kafka is a fast, scalable, distributed in nature by its design, partition