0% found this document useful (0 votes)
75 views

08-4. Room, LiveData, and ViewModel

This document discusses Room, LiveData, and ViewModel components of Android architecture. It provides an overview of how these components work together, with Room providing a database abstraction using entities and data access objects, LiveData for observable data, and ViewModel for separation of UI logic from data. Key aspects covered include how Room generates code for SQLite databases from entities, the role of data access objects for queries, and how LiveData works with the ViewModel to update the UI in response to database changes.

Uploaded by

Văn Dũng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

08-4. Room, LiveData, and ViewModel

This document discusses Room, LiveData, and ViewModel components of Android architecture. It provides an overview of how these components work together, with Room providing a database abstraction using entities and data access objects, LiveData for observable data, and ViewModel for separation of UI logic from data. Key aspects covered include how Room generates code for SQLite databases from entities, the role of data access objects for queries, and how LiveData works with the ViewModel to update the UI in response to database changes.

Uploaded by

Văn Dũng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Advanced Android Development V2

Storing data

Storing data with Room

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 1
and ViewModel License.
Room, LiveData, and
ViewModel

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 2
and ViewModel License.
Contents

● Architecture Components ● ViewModel


● Entity ● Repository
● DAO ● LiveData
● Room database ● Lifecycle

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 3
and ViewModel License.
Architecture
Components

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 4
and ViewModel License.
Architecture Components
A set of Android libraries for
structuring your app in a way
that is robust, testable, and
maintainable.

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 5
and ViewModel License.
Architecture Components
● Consist of best architecture practices + libraries
● Encourage recommended app architecture
● A LOT LESS boilerplate code
● Testable because of clear separation
● Fewer dependencies
● Easier to maintain

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 6
and ViewModel License.
Guide to app architecture

developer.android.com/arc
h

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 7
and ViewModel License.
Overview UI Controller
(activity/fragment)
Displays data and
forwards on UI
events
UI is notified of
changes using
observation LiveData Holds all the data
LiveData
LiveData ViewModel
needed for the UI

Single source of
truth for all app data;
Repository clean API for UI to
communicate with

LiveData RoomDatabase Manages local data


LiveData
Entity SQLite data source,
using objects
SQLite DAO

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 8
and ViewModel License.
MainActivity NewWordActivity
Observer

WordListAdapter

LiveData<List<Word>>
The RoomWordsSample
WordViewModel
app that you build in the
WordRepository practical implements this
Room

Word architecture
WordRoomDatabase

SQLite WordDao

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 9
and ViewModel License.
Room overview

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 10
and ViewModel License.
Room overview

Room is a robust SQL object


mapping library

● Generates SQLite Android code


● Provides a simple API for your
database
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 11
and ViewModel License.
Components of Room
● Entity: Defines schema of database table.
● DAO: Database Access Object
Defines read/write operations for database.
● Database: LiveData
LiveData RoomDatabase
Entity
A database holder.
Used to create or SQLite DAO
connect to database
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 12
and ViewModel License.
Entity

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 13
and ViewModel License.
Entity
● Entity instance = public class Person {
private int uid;
row in a database table private String firstName;
private String lastName;
● Define entities as POJO classes }

● 1 instance = 1 row
RoomDatabase
● Member variable = column LiveData
LiveData
Entity

name DAO
SQLite

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 14
and ViewModel License.
Entity instance = row in a database table
public class Person {
private int uid;
private String firstName;
private String lastName;
}
uid firstName lastName

12345 Aleks Becker

12346 Jhansi Kumar


This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 15
and ViewModel License.
Annotate entities
@Entity
public class Person {
@PrimaryKey (autoGenerate=true)
private int uid;

@ColumnInfo(name = "first_name")
private String firstName;

@ColumnInfo(name = "last_name")
private String lastName;

// + getters and setters if variables are private.


}
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 16
and ViewModel License.
@Entity annotation

@Entity(tableName = "word_table")

● Each @Entity instance represents an entity/row in a table

● Specify the name of the table if different from class name

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 17
and ViewModel License.
@PrimaryKey annotation
@PrimaryKey (autoGenerate=true)

● Entity class must have a field annotated as


primary key

● You can auto-generate unique key for each entity

● See Defining data using Room entities

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 18
and ViewModel License.
@NonNull annotation

@NonNull

● Denotes that a parameter, field, or


method return value can never be null
● Use for mandatory fields
● Primary key must use @NonNull

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 19
and ViewModel License.
@ColumnInfo annotation

first_name last_name
@ColumnInfo(name = "first_name")
private String firstName;
@ColumnInfo(name = "last_name")
private String lastName;

● Specify column name if different from


member variable name

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 20
and ViewModel License.
Getters, setters
Every field that's stored in the database must

● be public

OR

● have a "getter" method

… so that Room can access it


This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 21
and ViewModel License.
Relationships
users table
Use @Relation annotation to id

define related entities name

pet

Queries fetch all the returned


object's relations pets table
id

name

owner

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 22
and ViewModel License.
Many more annotations
For more annotations, see
Room package summary
reference

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 23
and ViewModel License.
Data access
object (DAO)

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 24
and ViewModel License.
Data access object

Use data access objects, or DAOs,


LiveData RoomDatabase
to access app data using the LiveData
Entity

Room persistence library SQLite DAO

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 25
and ViewModel License.
Data access object

● DAO methods provide abstract access to the app's


database
● The data source for these methods are entity objects
● DAO must be interface or abstract class
● Room uses DAO to create a clean API for your code

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 26
and ViewModel License.
Example DAO
@Dao
public interface WordDao {
@Insert
void insert(Word word);
@Update
public void updateWords(Word... words);
}
//... More queries on next slide...
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 27
and ViewModel License.
Example queries

@Query("DELETE FROM word_table")


void deleteAll();

@Query("SELECT * from word_table ORDER BY word ASC")


List<Word> getAllWords();

@Query("SELECT * FROM word_table WHERE word LIKE :word ")


public List<Word> findWord(String word);

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 28
and ViewModel License.
Room database

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 29
and ViewModel License.
Room

● Room is a robust SQL object


mapping library

● Generates SQLite Android code

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 30
and ViewModel License.
Room

● Room works with DAO and


Entities
LiveData RoomDatabase
LiveData
● Entities define the database Entity

schema SQLite DAO

● DAO provides methods to


access database

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 31
and ViewModel License.
Creating Room database
● Create public abstract class extending RoomDatabase
● Annotate as @Database
● Declare entities for database schema
and set version number

@Database(entities = {Word.class}, version = 1)


public abstract class WordRoomDatabase extends RoomDatabase

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 32
and ViewModel License.
Room class example
Entity
@Database(entities = {Word.class}, version = 1)
defines
public abstract class WordRoomDatabase DB schema
extends RoomDatabase { DAO for
database
public abstract WordDao wordDao();
Create
private static WordRoomDatabase INSTANCE; database as
singleton
// ... create instance here instance
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 33
and ViewModel License.
Use Database builder
● Use Room's database builder to create the database
● Create DB as singleton instance

private static WordRoomDatabase INSTANCE;


INSTANCE = Room.databaseBuilder(...)
.build();
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 34
and ViewModel License.
Specify database class and name
● Specify Room database class and database name
INSTANCE = Room.databaseBuilder(
context,
WordRoomDatabase.class, "word_database")
//...
.build();

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 35
and ViewModel License.
Specify onOpen callback
● Specify onOpen callback
INSTANCE = Room.databaseBuilder(
context,
WordRoomDatabase.class, "word_database")
.addCallback(sOnOpenCallback)
//...
.build();

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 36
and ViewModel License.
Specify migration strategy
● Specify migration strategy callback
INSTANCE = Room.databaseBuilder(
context.getApplicationContext(),
WordRoomDatabase.class, "word_database")
.addCallback(sOnOpenCallback)
.fallbackToDestructiveMigration()
.build();

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 37
and ViewModel License.
Room database creation example
static WordRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) { Check if database
synchronized (WordRoomDatabase.class) {
exists before
if (INSTANCE == null) {
creating it
INSTANCE = Room.databaseBuilder(
context.getApplicationContext(),
WordRoomDatabase.class, "word_database")
.addCallback(sOnOpenCallback)
.fallbackToDestructiveMigration()
.build();
}}}
return INSTANCE;
} Room, LiveData,
This work is licensed under a Creative
Commons Attribution 4.0 International
Android Developer Fundamentals V2 38
and ViewModel License.
Initialize DB in onOpen callback
private static RoomDatabase.Callback sOnOpenCallback =
new RoomDatabase.Callback(){
@Override
public void onOpen (@NonNull SupportSQLiteDatabase db){
super.onOpen(db);
initializeData();
}};

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 39
and ViewModel License.
Room caveats

● Compile-time checks of SQLite statements


● Do not run database operations on the main thread
● LiveData automatically runs query asynchronously on a
background thread when needed
● Usually, make your RoomDatabase a singleton

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 40
and ViewModel License.
ViewModel

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 41
and ViewModel License.
ViewModel

● View models are objects that


provide data for UI
components and survive
LiveData
LiveData
configuration changes. LiveData ViewModel

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 42
and ViewModel License.
ViewModel

● Provides data to the UI


● Survives configuration changes
● You can also use a ViewModel to share data between
fragments
● Part of the lifecycle library

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 43
and ViewModel License.
Survives configuration changes

Activity Instance
ViewModel

Activity UI
Rotation Event
Data

Re-created Activity
Instance

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 44
and ViewModel License.
ViewModel serves data
● ViewModel serves data to the UI
● Data can come from Room
database or other sources
● ViewModel's role is to return the
data, it can get help to find or
generate the data

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 45
and ViewModel License.
Best practice to use repository

Recommended best practice:


● Use a repository to do the work to
get the data
● Keeps ViewModel as clean
interface between app and data

Repository is discussed in next section


This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 46
and ViewModel License.
Restaurant analogy

● Customer requests meal ● UI requests data from


from server ViewModel
● Server takes order to ● ViewModel asks
chefs Repository for data
● Chefs prepare meal ● Repository gets data
● Server delivers meal to ● ViewModel returns data
customer to UI
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 47
and ViewModel License.
ViewModel example using repository
public class WordViewModel extends AndroidViewModel {
private WordRepository mRepository;
private LiveData<List<Word>> mAllWords;
// Initialize the repository and the list of words
public WordViewModel (Application application) {
super(application);
mRepository = new WordRepository(application);
mAllWords = mRepository.getAllWords();
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 48
and ViewModel License.
ViewModel example continued
LiveData<List<Word>> getAllWords() {
return mAllWords;
}
public void insert(Word word) {
mRepository.insert(word);
}
public void deleteWord(Word word) {
mRepository.deleteWord(word);
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 49
and ViewModel License.
Do not pass context into ViewModel
● Never pass context into ViewModel instances
● Do not store Activity, Fragment, or View instances or
their Context in the ViewModel
● An Activity can be destroyed and created many times
during the lifecycle of a ViewModel
● If you need application context, inherit from
AndroidViewModel
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 50
and ViewModel License.
ViewModel does not survive app closure
● ViewModel survives configuration changes,
not app shutdown
● ViewModel is not a replacement for
onSaveInstanceState()
(if you are not saving the data with Room)
● See Saving UI States

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 51
and ViewModel License.
Repository

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 52
and ViewModel License.
Repository

● Best practice, not part of


Architecture Components Repository
libraries
● Implement repository to
provide single, clean API
to app data

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 53
and ViewModel License.
Repository fetches or generates data

● Use repository to fetch data in


the background
● Analogy: chefs prepare meals
behind the scenes

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 54
and ViewModel License.
Multiple backends Repository

Dao Network

● Potentially, repository could manage query threads and


allow you to use multiple backends
● Example: in Repository, implement logic for deciding
whether to fetch data from a network or use results
cached in the database

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 55
and ViewModel License.
Repository example
public class WordRepository {
private WordDao mWordDao;
private LiveData<List<Word>> mAllWords;
WordRepository(Application application) {
WordRoomDatabase db = WordRoomDatabase.getDatabase(application);
mWordDao = db.wordDao();
mAllWords = mWordDao.getAllWords();
}
[... more code…]
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 56
and ViewModel License.
Get and insert data
LiveData<List<Word>> getAllWords() {
return mAllWords;
}

// Must insert data off the main thread


public void insert (Word word) {
new insertAsyncTask(mWordDao).execute(word);
}

[... more code…]


}

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 57
and ViewModel License.
Insert off main thread
private static class insertAsyncTask extends AsyncTask
<Word, Void, Void> {
private WordDao mAsyncTaskDao;
insertAsyncTask(WordDao dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(final Word... params) {
mAsyncTaskDao.insert(params[0]);
return null;
}
} This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 58
and ViewModel License.
LiveData

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 59
and ViewModel License.
LiveData
LiveData is a data holder class
that is aware of lifecycle events.
It keeps a value and allows this
LiveData ViewModel
value to be observed. LiveData
LiveData

Use LiveData to keep your UI


up to date with the latest and
greatest data. This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 60
and ViewModel License.
LiveData

● LiveData is observable data


● Notifies observer when data
changes
● Is lifecycle aware:
knows when device rotates
or app stops

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 61
and ViewModel License.
Use LiveData to keep UI up to date
● Create an observer that
observes the LiveData
● LiveData notifies Observer
objects when the observed
data changes
● Your observer can update the
UI every time the data changes

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 62
and ViewModel License.
Creating LiveData

To make data observable, return it as LiveData:

@Query("SELECT * from word_table)


LiveData<List<Word>> getAllWords();

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 63
and ViewModel License.
Using LiveData with Room

Room generates all


the code to update the
LiveData when the
database is updated

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 64
and ViewModel License.
Passing LiveData through layers

When you pass live data through the layers of your app
architecture, from a Room database to your UI, that data
must be LiveData in all layers:
● DAO
● ViewModel
● Repository

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 65
and ViewModel License.
Passing LiveData through layers
● DAO:
@Query("SELECT * from word_table")
LiveData<List<Word>> getAllWords();
● Repository:
LiveData<List<Word>> mAllWords =
mWordDao.getAllWords();
● ViewModel:
LiveData<List<Word>> mAllWords =
mRepository.getAllWords();
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 66
and ViewModel License.
Observing LiveData

● Create the observer in onCreate() in the Activity


● Override onChanged() in the observer to update the UI
when the data changes

When the LiveData changes, the observer is notified and


its onChanged() is executed

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 67
and ViewModel License.
Observing LiveData: example
final Observer<String> nameObserver =
new Observer<String>() {
@Override
public void onChanged(@Nullable final String newName) {
// Update the UI, in this case, a TextView.
mNameTextView.setText(newName);
}
};

mModel.getCurrentName().observe(this, nameObserver);
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 68
and ViewModel License.
No memory leaks

● Observers are bound to Lifecycle objects


which are objects that have an Android Lifecycle
● Observers clean up after themselves when their
associated lifecycle is destroyed

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 69
and ViewModel License.
LiveData is always up to date

● If a lifecycle object becomes inactive,


it gets the latest data when it becomes
active again
● Example: an activity in the background
gets the latest data right after it
returns to the foreground

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 70
and ViewModel License.
LiveData handles configuration changes
If an activity or fragment
is re-created due to a
configuration change
such as device rotation,
the activity or fragment
immediately receives the
latest available data

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 71
and ViewModel License.
Share resources

● You can extend a LiveData object using the singleton


pattern, for example for services or a database
● The LiveData object connects to the system service
once, and then any observer that needs the resource can
just watch the LiveData object
● See Extend LiveData

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 72
and ViewModel License.
Lifecycle

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 73
and ViewModel License.
Lifecycle-aware components

Instead of managing lifecycle-dependent


components in the activity's lifecycle methods,
onStart(), onStop(), and so on, you can make
any class react to lifecycle events

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 74
and ViewModel License.
Lifecycle-aware components

● Lifecycle-aware components perform actions in


response to a change in the lifecycle status of
another component
● For example, a listener could start and stop itself in
response to an activity starting and stopping

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 75
and ViewModel License.
Use cases

● Switch between coarse and fine-grained location updates


depending on app visibility
● Stop and start video buffering
● Stop network connectivity when app is in background
● Pause and resume animated drawables

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 76
and ViewModel License.
Lifecycle library

● Import the android.arch.lifecycle package


● Provides classes and interfaces that let you build lifecycle-
aware components that automatically adjust their behavior
based on lifecycle state of activity or fragment
● See Handling Lifecycles with Lifecycle-Aware Components

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 77
and ViewModel License.
LifecycleObserver interface
● LifecycleObserver has an Android lifecycle.
● It does not have any methods, instead, uses
OnLifecycleEvent annotated methods.

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 78
and ViewModel License.
@OnLifecycleEvent
@OnLifecycleEvent indicates life cycle methods

@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void start() {...}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void start() {...}

See Lifecycle.event reference for more lifecycle events

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 79
and ViewModel License.
POJOs can be life cycle aware
You can make any class In these pictures,
react to lifecycle events
the Toast is
created by a plain
old Java class
when app starts
or device rotates
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 80
and ViewModel License.
Adding lifecycle awareness to a POJO
public class Aquarium {

// Constructor takes Application and lifecycle


public Aquarium(final Application app,
Lifecycle lifecycle) {
...
}

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 81
and ViewModel License.
Constructor for lifecycle aware POJO
public Aquarium(final Application app, Lifecycle lifecycle) {
// Add a new observer to the lifecycle.
lifecycle.addObserver(new LifecycleObserver() {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void start() {
Toast.makeText(app, "LIGHTS ON", Toast.LENGTH_SHORT).show();
}
});
}

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 82
and ViewModel License.
Creating an instance
public class MainActivity extends AppCompatActivity {
private Aquarium myAquarium;
protected void onCreate(...) {
...
// Create aquarium.
// Pass context and this activity's lifecycle
myAquarium = new Aquarium(this.getApplication(),
getLifecycle());
}
} This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 83
and ViewModel License.
What's next?

● Concept chapter: 10.1 Room, LiveData, and ViewModel


● Practical: 10.1A : Room, LiveData, and ViewModel
● Practical: 10.1B : Room, LiveData, and ViewModel

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 84
and ViewModel License.
END

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 85
and ViewModel License.

You might also like