Architecture Components

Posted LittleEyes

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 

以上是关于Architecture Components的主要内容,如果未能解决你的问题,请参考以下文章

2.0.Architecture components架构组件

Building Maintainable Software-java篇之Keep Architecture Components Balanced

2.1.1.Architecture components_Lifecycles

2.1.3.Architecture components_LiveData

Android Architecture Components使用介绍

Android Architecture Components使用介绍