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

10.1 - Room, LiveData, and ViewModel

The document discusses Room, LiveData, and ViewModel which are part of Android's Architecture Components. It provides an overview of how these components work together, including how entities define database tables, DAOs define database operations, and RoomDatabase manages the SQLite database. LiveData is used to observe database changes and notify views, while ViewModel stores UI-related data and survives configuration changes.

Uploaded by

Tushar Vaze
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

10.1 - Room, LiveData, and ViewModel

The document discusses Room, LiveData, and ViewModel which are part of Android's Architecture Components. It provides an overview of how these components work together, including how entities define database tables, DAOs define database operations, and RoomDatabase manages the SQLite database. LiveData is used to observe database changes and notify views, while ViewModel stores UI-related data and survives configuration changes.

Uploaded by

Tushar Vaze
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 85

Advanced Android Development V2

Storing data
with Room
Lesson 10

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 1
and ViewModel national License
10.1 Room, LiveData, and
ViewModel

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 2
and ViewModel national License
Contents

● Architecture Components ● ViewModel


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

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 3
and ViewModel national License
Architecture
Components

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 4
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 5
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 6
and ViewModel national License
Guide to app architecture

developer.android.com/arch

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 7
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 8
and ViewModel national License
MainActivity NewWordActivity
Observer

WordListAdapter

LiveData<List<Word>> The RoomWordsSample


WordViewModel

app that you build in the

Room
WordRepository
practical implements this
Word architecture
WordRoomDatabase

SQLite WordDao

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 9
and ViewModel national License
Room overview

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 10
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 11
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 12
and ViewModel national License
Entity

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 13
and ViewModel national 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 SQLite DAO

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 14
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 15
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 16
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 17
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 18
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 19
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 20
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 21
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 22
and ViewModel national License
Many more annotations

For more annotations, see


Room package summary re
ference

This work is licensed under a


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

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 24
and ViewModel national License
Data access object

Use data access objects, or DAOs, RoomDatabase


LiveData
to access app data using the
LiveData
Entity

Room persistence library SQLite DAO

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 25
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 26
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 27
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 28
and ViewModel national License
Room database

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 29
and ViewModel national License
Room

● Room is a robust SQL object


mapping library

● Generates SQLite Android code

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 30
and ViewModel national License
Room
● Room works with DAO and
Entities
RoomDatabase
● Entities define the database LiveData
LiveData
Entity

schema SQLite DAO

● DAO provides methods to


access database

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 31
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 32
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 33
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 34
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 35
and ViewModel national License
Specify onOpen callback
● Specify onOpen callback
INSTANCE = Room.databaseBuilder(
context,
WordRoomDatabase.class, "word_database")
.addCallback(sOnOpenCallback)
//...
.build();
This work is licensed under a
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 36
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 37
and ViewModel national 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;
} This work is licensed under a
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 38
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 39
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 40
and ViewModel national License
ViewModel

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 41
and ViewModel national License
ViewModel

● View models are objects that


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

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 42
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 43
and ViewModel national License
Survives configuration changes

Activity Instance
ViewModel

Activity UI
Rotation Event
Data

Re-created Activity
Instance

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 44
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 45
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 46
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 47
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 48
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 49
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 50
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 51
and ViewModel national License
Repository

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 52
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 53
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 54
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 55
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 56
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 57
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 58
and ViewModel national License
LiveData

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 59
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 60
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 61
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 62
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 63
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 64
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 65
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 66
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 67
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 68
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 69
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 70
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 71
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 72
and ViewModel national License
Lifecycle

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 73
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 74
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 75
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 76
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 77
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 78
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 79
and ViewModel national 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
Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 80
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 81
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 82
and ViewModel national 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());
}
} Room, LiveData,
This work is licensed under a
Android Developer Fundamentals V2 Creative Commons Attribution 4.0 Inter 83
and ViewModel national 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


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 84
and ViewModel national License
END

This work is licensed under a


Android Developer Fundamentals V2 Room, LiveData, Creative Commons Attribution 4.0 Inter 85
and ViewModel national License

You might also like