1 of 52

Architectural Components

Architectural, UI & Think Components

2 of 52

Design of Mobile

  • Code: Design Patterns To do the thing right

Starting with the basics of writing clean code (SOLID, Rx, TDD & DI with Kotlin)

  • Interface: Design UX/UI To do the right thing

Applying Material Design U&I with the latest research we build intuitive UX (engage & retain) and responsive UI (optimistic rendering).

  • Product: Design Thinking The right thing to do

Design Thinking uses iterative data driven ethnography to build empathy and solve major pain points, ensuring we are build the correct product.

https://academy.realm.io/posts/droidcon-boston-siamak-ashrafi-real-world-android-native-development/

3 of 52

We have good base … not a framework!

4 of 52

App components

App components are the essential building blocks of an Android app ??? NO !!!

  • Activities - The entry point for interacting with the user.
  • Services - General-purpose entry point for keeping an app running in the background.
  • Broadcast receivers - Component that enables the system to deliver events to the app outside of a regular user flow
  • Content providers - Manages a shared set of app data that you can store in the file system, in a SQLite database, on the web, or on any other persistent storage location that your app can access.

5 of 52

The Problem

"How should I design my Android application? What kind of MVC pattern should I use? What should I use for an event bus?" “

It is probably better to call the core Android APIs a ‘system framework.’ For the most part, the platform APIs we provide are there to define how an application interacts with the operating system; but for anything going on purely within the app, these APIs are often just not relevant.” - Dianne Hackborn

https://plus.google.com/+DianneHackborn/posts/FXCCYxepsDU

6 of 52

Problem Resolution → Solution

Android Architecture Components work together to implement a sane app architecture, while they individually address developer pain points.

Pieces needed to finish the platform:

  • Persist Data
  • Manage Lifecycles
  • Modular
  • Defence Against Common errors
  • Less Boiler Plate

7 of 52

Fixing Android UIssues

  • Android Material Components - Create beautiful apps with modular and customizable UI components.

  • ConstraintLayout - available in an API library that's compatible with Android 2.3 (API level 9) and higher. This page provides a guide to building a layout with ConstraintLayout in Android Studio 2.3 or higher

8 of 52

What Happened? & Why Important?

First time the Android Team is proposing an architecture for Android.

This is a significant shift from the past where The Android Team did not give any direction or advice on how to structure an Android App.

Android UI Team add a constraint library

UI can handle different screen sizes and rotation

First time the Android Team is supporting a new language.

Although this language is compatible with java it is far better because it started with baking in Effective Java (JDK9)

Android Material Design released Material Components

UI components built with “best practice”

9 of 52

Android Architecture Components

  1. Lifecycle - holds the information about the lifecycle state of a component
  2. ViewModel - provide data for UI components and survive config change
  3. LiveData - between the data and the view is observable data holder
  4. Room - provides an abstraction layer over SQLite to allow fluent access

https://developer.android.com/topic/libraries/architecture/guide.html

10 of 52

Lifecycle Aware Components

11 of 52

Android Activity LifeCycle / Fragment LifeCycle

12 of 52

AsyncTask

AsyncTask (API Level 3) allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

  • If you fetch the data directly in the activity or fragment, your users will suffer from lack of responsiveness due to performing potentially slow queries from the UI thread.
  • If you fetch the data from another thread, perhaps with AsyncTask, then you're responsible for managing both the thread and the UI thread through various activity or fragment lifecycle events, such as onDestroy() and configurations changes.
  • Configuration changes can mess things up
  • Pausing an activity doesn’t pause the AsyncTask
  • A fair amount of boilerplate code (which means more possible errors)

13 of 52

Rotate Phone

14 of 52

AsyncTaskLoader & CursorLoader (DB)

AsyncTaskLoader(API Level 11) & CursorLoader

Loaders solve these problems and includes other benefits. For example:

  • Loaders run on separate threads to prevent janky or unresponsive UI.
  • Loaders simplify thread management by providing callback methods when events occur.
  • Loaders persist and cache results across configuration changes to prevent duplicate queries.
  • Loaders can implement an observer to monitor for changes in the underlying data source. For example, CursorLoader automatically registers a ContentObserver to trigger a reload when data changes.

Making loading data lifecycle aware (2/3/2016)

15 of 52

Handling Lifecycles

The android.arch.lifecycle package provides classes and interfaces that let you build lifecycle-aware components — which are components that can automatically adjust their behavior based on the current lifecycle of an activity or fragment.

Lifecycle Aware Data Loading with Architecture Components(5/17/2017)

16 of 52

Lifecycle Owner

LifecycleOwner is a single method interface that denotes that the class has a Lifecycle. It has one method, getLifecycle(), which must be implemented by the class.

17 of 52

Lifecycle [Activity / Fragment]

Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state.

18 of 52

Lifecycle Observer

Class My<Function>Listener implements LifecycleObserver

@OnLifecycleEvent(Lifecycle.Event.ON_START)

void start() { if (enabled) { // connect }}

https://developer.android.com/reference/android/arch/lifecycle/Lifecycle.Event.html

ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DISTROYED, ON_ANY ...

if (lifecycle.getState().isAtLeast(STARTED)) {

// connect if not connected }

19 of 52

Events & States

20 of 52

LifeCycles (Activity & Fragments)

Lifecycle is a class that holds the information about the lifecycle state

  • Keep your UI controllers (activities and fragments) as lean as possible.
  • Try to write data-driven UIs with ViewModel & LiveData.
  • Put your data logic in your ViewModel class.
  • Use Data Binding to maintain a clean interface between your views and the UI controller.
  • Create a Presenter class to handle UI modifications.
  • Never reference a View or Activity context in your ViewModel.

21 of 52

LiveData

22 of 52

LiveData Flow

23 of 52

LiveData

public class typeLiveData extends LiveData<type> { @Override ...

onActive() - This method is called when the LiveData has an active observer. This means we need to start observing the updates.

onInactive() -This method is called when the LiveData does not have any active observers. This is important because staying connected consumes significant battery power without any benefit.

setValue() - Calling this method updates the value of the LiveData instance and notifies active observers about the change.

24 of 52

Using LiveData

25 of 52

Transformations of LiveData

Provides a Transformations class that includes helper methods for these operations.

  • Transformations.map()

Applies the given function on the main thread to each value emitted by source LiveData and returns LiveData, which emits resulting values.

  • Transformations.switchMap()

Creates a LiveData, let's name it swLiveData, which follows next flow: it reacts on changes of trigger LiveData, applies the given function to new value of trigger LiveData and sets resulting LiveData as a "backing" LiveData to swLiveData. "Backing" LiveData means, that all events emitted by it will retransmitted by swLiveData.

26 of 52

Advantages of LiveData

LiveData is a data holder class that keeps a value and is observed.

  • No memory leaks
  • No crashes due to stopped activities
  • Always up to date data
  • Proper configuration change
  • Sharing Resources
  • No more manual lifecycle handling

27 of 52

ViewModel

28 of 52

ViewModel

Provide data for UI components and survive config change

    • Lifecycles provides a new class called ViewModel, a helper class for the UI controller which is responsible for preparing the data for the UI.
    • ViewModels usually expose this information via LiveData or Android Data Binding.
    • LiveData handles the notification side of things while the ViewModel makes sure that the data is retained appropriately.

29 of 52

ViewModel

30 of 52

ViewModel InAction

31 of 52

Sharing Data Between Fragments

  • The activity does not need to do anything, or know anything about this communication.
  • Fragments don’t need to know about each other besides the SharedViewModel contract. If one of them disappears, the other one keeps working as usual.
  • Each fragment has its own lifecycle, and is not affected by the lifecycle of the other one. In fact, in a UI where one fragment replaces the other one, the UI works without any problems.

32 of 52

Room Persistence Library

33 of 52

Room Persistence Library

Room provides an abstraction layer over SQLite to allow fluent database access while - harnessing the full power of SQLite.

3 major components in Room:

  • Database:
  • Entity:
  • DAO:

34 of 52

Entity

When a class is annotated with @Entity and is referenced in the entities property of a @Database annotation, Room creates a database table for that entity in the database.

35 of 52

DAO

DAOs abstract access to the database in a clean way (normal SQL).

(CRUD)

@Insert

@Query

@Update

@Delete

36 of 52

Database

You can use this component to create a database holder. The annotation defines the list of entities, and the class's content defines the list of data access objects (DAOs) in the database.

37 of 52

ROOM Layout

38 of 52

Android App Architecture

39 of 52

Arch Guiding principles

  • The entry points you define in your manifest - activities, services, broadcast receivers, etc. - are not the source of data.
  • Be merciless in creating well defined boundaries of responsibility between various modules of your app.
  • Expose as little as possible from each module
  • As you define the interaction between the modules, think about how to make each one testable in isolation.

40 of 52

Arch Guiding principles

  • The core of your app is what makes it stand out from the rest.
  • Persist as much relevant and fresh data as possible so that your app is usable when the device is in offline mode.
  • Your repository should designate one data source as the single source of truth. -- For more information, see Single source of truth.

41 of 52

Architectural components

42 of 52

Architecture

43 of 52

Final Reference Architecture

Firestore UI

LiveData

44 of 52

Building the user interface

  • A ViewModel provides the data for a specific UI component.

Handles the communication with the business part of data handling & is not affected by configuration changes such as recreating an activity due to rotation.

  • LiveData is an observable data holder.

It lets the components in your app observe LiveData objects for changes without creating explicit and rigid dependency paths between them.

  • Repository modules are responsible for handling data operations.

Mediators between different data sources (persistent model, web service, cache, etc.)

45 of 52

Constraint Library

46 of 52

Android Material components

47 of 52

CodeLabs & GitHub.

This codelab introduces you to lifecycle-aware architecture components for building Android apps. CodeLab

The new Room Persistence Library guarantee SQL statements at compile-time and removes boilerplate code related to storing data locally in SQLite CodeLab

Github:

BasicSample - Shows how to persist data using a SQLite database and Room. Also uses ViewModels and LiveData.

PersistenceContentProviderSample - Shows how to expose data via a Content Provider using Room.

GithubBrowserSample - An advanced sample that uses the Architecture components, Dagger and the Github API. Requires Android Studio 3.0 canary 1

48 of 52

TDD

  • User Interface & Interactions:

Android UI Instrumentation test.Espresso test.

  • ViewModel:

The ViewModel can be tested using a JUnit test.

  • UserRepository:

You can test the UserRepository with a JUnit test as well.

  • UserDao:

Using instrumentation tests with in-memory database

49 of 52

Kotlin

Kotlin fixes a series of issues that Java suffers from

50 of 52

Think With Google

Analytics and data is essential to developing, optimising and marketing apps in the best possible ways to increase users, reach and return on investment. The best apps in the world are constantly checked and analysed by their creators, fine tuned to reach the right audience, to improve their experience and to bring them the content or the services they want.

http://appindex.com/blog/big-list-app-analytics-tools/

Google:

https://developers.google.com/analytics/

Secrets to App Success on Google Play (A / B Testing)

Google Marketing Research & Digital Trends https://www.thinkwithgoogle.com/

*In God we trust … Everyone else bring DATA!

51 of 52

Think with Google

52 of 52

Leaning “Think With Google” to Design

Non Google Play Distribution

  • AppChina has 30 million users
  • Tencent App Gem has 80 million users
  • Anzhi has 25 million users
  • The Amazon Appstore has 25 million apps downloaded every month
  • The Opera Mobile Store has 30 million apps downloaded every month
  • AppChina has 600 million apps downloaded every month
  • Wandoujia, China’s largest alternative app store, has a staggering 200 million users with over 30 million apps downloaded every day – 500,000 new users are acquired every day
  • Samsung Apps is preinstalled on more than 100 million Galaxy smartphones

Google Play Store* (Developers Page)

https://developer.android.com/google/play/dist.html (use staged rollouts)

*Understanding Statistically Valid Performance