首页 > 代码库 > Architecture Components

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