博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Architecture Components
阅读量:5931 次
发布时间:2019-06-19

本文共 5235 字,大约阅读时间需要 17 分钟。

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.

@Entitypublic 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

@Daopublic interface TrailDao{    //Create,read,update,delete examples    @Insert(onConflict=IGNORE)    void insertTrail(Trail trail)     @Query("SELECT * FROM Trail")    public  List
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
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

@Daopublic interface TrailDao{    //Create,read,update,delete examples    @Insert(onConflict=IGNORE)    void insertTrail(Trail trail)     @Query("SELECT * FROM Trail")    public LiveData
> 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
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<
>> 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 onCreatetrailListViewModel=ViewModelProviders.of(this).get(TrailViewModel.class);//Code to set up the RecyclerView omittedtrailListViewModel.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.

 

转载于:https://www.cnblogs.com/ryq2014/p/7126561.html

你可能感兴趣的文章
iOS_开发中遇到的那些问题_1
查看>>
教您在终端模拟器中调节文字大小
查看>>
win10: This file can't be opened
查看>>
curl
查看>>
[LeetCode] Sentence Similarity 句子相似度
查看>>
Android——复制项目出现Application Installation Failed
查看>>
html5--6-56 阶段练习5-翻转效果
查看>>
我的进程去哪儿了,谁杀了我的进程
查看>>
16.其它内置指令
查看>>
R t-test cor.test
查看>>
C#实现局部峰值查找,功能对应Matlab中的findpeaks.m
查看>>
SpringBoot系统列 1 - HelloWorld!
查看>>
运行时系统:类型系统、派发系统--运行时系统是一个解释系统
查看>>
python gb2312 转换为 utf-8
查看>>
为何成员函数指针模板不能像函数指针模板一样有简单的声明方式呢
查看>>
《Scala, Erlang, F#作者讨论函数式语言》有感
查看>>
Android IOS WebRTC 音视频开发总结(六八)-- Google: What's next for WebRTC
查看>>
Memcached查看和清理
查看>>
C#非泛型集合类-使用HashTable元素操作
查看>>
JFinal 入门
查看>>