Slide 1

Slide 1 text

Android Architecture Components LifeCycle , LiveData , Room and ViewModel

Slide 2

Slide 2 text

Agenda ● What is Architecture ? ● Common Problems ● Why to use Android Architecture Components ? ● LifeCycle ● ViewModel ● LiveData ● Room

Slide 3

Slide 3 text

What is Architecture ? Software application architecture is the process of defining a structured solution that meets all of the technical and operational requirements, while optimizing common quality attributes such as performance, security, and manageability. It involves a series of decisions based on a wide range of factors, and each of these decisions can have considerable impact on the quality, performance, maintainability, and overall success of the application

Slide 4

Slide 4 text

What is Architecture ?

Slide 5

Slide 5 text

What is Architecture ? Separation of Concerns

Slide 6

Slide 6 text

Common Developer Problems ● Multiple Entry Point ● Constantly Switching Flow and Tasks ● Screen Rotation

Slide 7

Slide 7 text

Architecture Patterns ● MVC (Model-View-Controller) ● MVP (Model-View-Presenter) ● MVVM (Model-View-ViewModel) ● VP (View-Presenter)

Slide 8

Slide 8 text

Our Expectations

Slide 9

Slide 9 text

Reality

Slide 10

Slide 10 text

Why Architecture Components ? Persist Data Manage LifeCycle Modular Defense Against Common Errors Less Boilerplate

Slide 11

Slide 11 text

Simple App App UI/UX ROOM Modifies,requests or generates data for database Response Back LIVE DATA

Slide 12

Slide 12 text

Components 4. Room 1. LifeCycle 2. LiveData 3. ViewModel

Slide 13

Slide 13 text

Dependencies //Room compile 'android.arch.persistence.room:runtime:1.0.0' annotationProcessor 'android.arch.persistence.room:compiler:1.0.0' //LifeCycle and ViewModel compile 'android.arch.lifecycle:runtime:1.0.0' compile 'android.arch.lifecycle:extensions:1.0.0' annotationProcessor 'android.arch.lifecycle:compiler:1.0.0'

Slide 14

Slide 14 text

LifeCycle : Problems 2. Untimely UI updates 1. Activity/Fragment LifeCycle 4. Screen Rotation 3. Broadcast Receivers

Slide 15

Slide 15 text

LifeCycle LifeCycle Owner : LifeCycle Owner are the objects with lifecycle ,like Activities and Fragments LifeCycle Owners: ( Activities/Fragments ) LifeCycle Observer : LifeCycle Observer observe LifeCycleOwners , and are notifies of lifecycle changes LifeCycle Observer (Ex: LiveData)

Slide 16

Slide 16 text

LifeCycle @Override public void onCreate(...) { myLocationListener = new MyLocationListener(this, location -> { // update UI }); } @Override public void onStart() { super.onStart(); myLocationListener.start(); } @Override public void onStop() { super.onStop(); myLocationListener.stop(); }

Slide 17

Slide 17 text

LifeCycle @Override public void onCreate(...) { myLocationListener = new MyLocationListener(this, location -> { // update UI }); } @Override public void onStop() { super.onStop(); myLocationListener.stop(); } @Override public void onStart() { super.onStart(); Util.checkUserStatus(result -> { // what if this callback is invoked AFTER activity is stopped? if (result) { myLocationListener.start(); } }); }

Slide 18

Slide 18 text

MyLocationListener public class MyLocationListner implements LifecycleObserver { } //Add this our MainActivity getLifecycle().addObserver(new MyLocationListner()); @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void connectListener() { ... } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void disconnectListener() { ... }

Slide 19

Slide 19 text

MyLocationListener class MyLocationListener implements LifecycleObserver { } private boolean enabled = false; public MyLocationListener(Context context, Lifecycle lifecycle, Callback callback) { ... } public void enable() { enabled = true; if (lifecycle.getCurrentState().isAtLeast(STARTED)) { // connect if not connected } } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void stop() { // disconnect if connected } @OnLifecycleEvent(Lifecycle.Event.ON_START) void start() { if (enabled) { // connect } }

Slide 20

Slide 20 text

MainActivity class MainActivity extends AppCompatActivity { private MyLocationListener myLocationListener; public void onCreate(...) { } } myLocationListener = new MyLocationListener(this,getLifecycle(),location -> { // update UI }); Util.checkUserStatus(result -> { if (result) { myLocationListener.enable(); } });

Slide 21

Slide 21 text

LifeCycle : Use Cases 2. Stopping and starting video buffering 1. Location updates 3. Pausing and resuming animatable drawables

Slide 22

Slide 22 text

ViewModel The ViewModel class is designed store and manage UI-related data so that data survives the configuration changes such as screen rotations ViewModel: public class MyViewModel extends ViewModel{ } AndroidViewModel with context: public class MyViewModel extends AndroidViewModel { public MyViewModel(@NonNull Application application) { super(application); } }

Slide 23

Slide 23 text

ViewModel LifeCycle

Slide 24

Slide 24 text

Create ViewModel public class MyViewModel extends ViewModel { private int mRotationCount; public int getRotationCount() { mRotationCount = mRotationCount + 1; return mRotationCount; } }

Slide 25

Slide 25 text

Implement ViewModel @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //Get view model instance MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class); //set the increment value mRotationCountTextView.setText("" + myViewModel.getRotationCount());

Slide 26

Slide 26 text

Context ViewModel public class MyViewModel extends AndroidViewModel { private NotificationManager mNotificationManager; } public MyViewModel(@NonNull Application application) { super(application); mNotificationManager = (NotificationManager) application. getSystemService(Context.NOTIFICATION_SERVICE); }

Slide 27

Slide 27 text

ViewModel : Use Cases 2. Shared between fragments 1. Retain State 3. Replacing loaders

Slide 28

Slide 28 text

LiveData 1. LiveData is observable data holder. 2. It notifies the observers when data changes so that you can update the UI. 3. It is also Life Cycle Aware

Slide 29

Slide 29 text

LiveData : Pros 1. UI Matches your data state 2. No Memory leak 3. No more manual lifecycle handling

Slide 30

Slide 30 text

Create LiveData Object public class NameViewModel extends ViewModel { // Rest of the ViewModel... } // Create a LiveData with a String private MutableLiveData mCurrentName; public MutableLiveData getCurrentName() { if (mCurrentName == null) { mCurrentName = new MutableLiveData(); } return mCurrentName; }

Slide 31

Slide 31 text

Observe LiveData Objects private NameViewModel mModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } // Get the ViewModel. mModel = ViewModelProviders.of(this).get(NameViewModel.class); // Create the observer which updates the UI. final Observer nameObserver = new Observer() { @Override public void onChanged(@Nullable final String newName) { // Update the UI, in this case, a TextView. mNameTextView.setText(newName); } }; // Observe the LiveData, passing in this activity as the // LifecycleOwner and the observer. mModel.getCurrentName().observe(this, nameObserver);

Slide 32

Slide 32 text

Update LiveData Objects mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String anotherName = "John Doe"; mModel.getCurrentName().setValue(anotherName); } });

Slide 33

Slide 33 text

Database ??

Slide 34

Slide 34 text

Room Room is a robust SQL Object Mapping Library

Slide 35

Slide 35 text

Plain Old Java Object (POJO) Old POJO Room POJO public class User { private int uid; private String firstName; private String lastName; private int age; private Date dateOfJoining; } public class User { private int uid; private String firstName; private String lastName; private int age; private Date dateOfJoining; } @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "first_name") @Entity @ColumnInfo(name = "last_name")

Slide 36

Slide 36 text

UserDao.java public interface UserDao { } @Insert void insertAll(List users); @Delete void delete(User user); @Update void updateUser(User user); @Query("SELECT * FROM user") List getAll(); @Dao @Query("SELECT * FROM user WHERE uid = :userID") User findUserById(int userID);

Slide 37

Slide 37 text

UserDao.java public interface UserDao { } @Insert void insertAll(List users); @Delete void delete(User user); @Update void updateUser(User user); @Query("SELECT * FROM user") LiveData> getAll(); @Dao @Query("SELECT * FROM user WHERE uid = :userID") User findUserById(int userID);

Slide 38

Slide 38 text

Setup Room Database public abstract class AppDatabase extends RoomDatabase { } public abstract UserDao userDao(); @Database(entities = {User.class}, version = 1) @TypeConverters({Converters.class})

Slide 39

Slide 39 text

Build Room Database public class AppController extends Application { private static AppController appController; private AppDatabase appDatabase; @Override public void onCreate() { super.onCreate(); appController = this; } public static AppDatabase getAppDatabase() { return appController.appDatabase; } } //Initialize the room database with database name appDatabase = Room.databaseBuilder(this, AppDatabase.class, "user-database") .fallbackToDestructiveMigration() .build();

Slide 40

Slide 40 text

Display data public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); List userList = AppController .getAppDatabase() .userDao() .getAll(); //Update List in adapter } }

Slide 41

Slide 41 text

UserModel public class UserModel extends ViewModel { private final UserDao userDao; public UserModel() { userDao = AppController .getAppDatabase() .userDao(); } public LiveData> getAllUser() { return userDao.getAll(); } }

Slide 42

Slide 42 text

MainActivity public class MainActivity extends AppCompatActivity { private UserModel userModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Setup your UI } } userModel = ViewModelProviders.of(this).get(UserModel.class); userModel.getAllUser().observe(this, new Observer>() { @Override public void onChanged(@Nullable List userList) { // updateUI } });

Slide 43

Slide 43 text

Thank you burhanrashid52 Burhanuddin Rashid Resources : ● Android Architecture Components : http://bit.ly/2hGRxoc ● Exploring Architecture Components : http://bit.ly/2j1Pvvv Multidots Inc. https://www.multidots.com/