SlideShare une entreprise Scribd logo
1  sur  64
Télécharger pour lire hors ligne
Building Modern Apps using
Android Architecture
Components
Hassan Abid
GDE Android - Singapore
@hassanabidpk
Google I/O Talks
! Android Jetpack: what's new in Android Support Library
! Android Jetpack: what's new in Architecture Components
! Modern Android development: Android Jetpack, Kotlin, and more
! Android Jetpack: how to smartly use Fragments in your UI
! Android Jetpack: manage UI navigation with Navigation Controller
! Android Jetpack: manage infinite lists with RecyclerView and Paging
! Android Jetpack: easy background processing with WorkManager
! Android Slices: build interactive results for Google Search
! Android Jetpack: sweetening Kotlin development with Android KTX
! Protips: a fresh look at advanced topics for Android experts
Android Dev Summit 2018 Talks
! https://www.youtube.com/playlist?list=PLWz5rJ2EKKc8WFYCR9esqGGY0vOZm2l6e
AndroidX : Android Extension Libraries
! AndroidX fully replaces the Support Library by
providing feature parity and new libraries
! Added to Android Open Source Project
AndroidX
AndroidX: "Android Extension Libraries"
android.support.v4.view.ViewCompat
→ androidx.core.view.ViewCompat
android.support.v7.app.AppCompatActivity
→ androidx.appcompat.app.AppCompatActivity
android.arch.persistence.room.RoomDatabase
→ androidx.room.RoomDatabase
AndroidX
! Strict Semantic versioning rule
○ Reset to 1.0.0
Refactor to AndroidX
Migration from 28.0.0
Recommended Architecture
Architecture Components
! LifeCycle (2.0.0 Stable)
! Data-binding (Stable, 3.2 New!)
! ViewModel (Stable, New!)
! LiveData (Stable, New!)
! Room (2.1 New!)
! Paging (2.1 New)
! WorkManager (New!)
! Navigation (New!)
https://developer.android.com/jetpack/docs/release-notes
Adding Components to your project
allprojects {
repositories {
jcenter()
google()
}
}
Example : LifeCycle - include ViewModel and
LiveData (Pre-AndroidX)
dependencies {
def lifecycle_version = “2.0.0“
// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
// alternatively - just ViewModel. use -ktx for Kotlin
implementation "android.arch.lifecycle:viewmodel:$lifecycle_version"
}
Example : LifeCycle (AndroidX)
dependencies {
def lifecycle_version = "2.0.0"
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
// alternatively - just ViewModel use -ktx for Kotlin
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version" }
LifeCycle
LifeCycle
LifeCycle Problem
internal class MyLocationListener(
private val context: Context,
private val callback: (Location) -> Unit
) {
fun start() {
// connect to system location service
}
fun stop() {
// disconnect from system location service
}
}
LifeCycle Problem
class MyActivity : AppCompatActivity() {
private lateinit var myLocationListener: MyLocationListener
override fun onCreate(...) {
myLocationListener = MyLocationListener(this) { location ->
// update UI
}
}
public override fun onStart() {
super.onStart()
myLocationListener.start()
// manage other components that need to respond
// to the activity lifecycle
}
public override fun onStop() {
super.onStop()
myLocationListener.stop()
// manage other components that need to respond
// to the activity lifecycle
}
}
Solution
! LifeCycle Owners : Objects with LifeCycle like Activities and
Fragments
! LifeCycle Observers : Observe Lifecycle owners and are
notified life cycle changes
Solution
class MyActivity : AppCompatActivity() {
private lateinit var myLocationListener: MyLocationListener
override fun onCreate(...) {
myLocationListener = MyLocationListener(this, lifecycle) { location ->
// update UI
}
Util.checkUserStatus { result ->
if (result) {
myLocationListener.enable()
}
}
}
}
Solution
internal class MyLocationListener(
private val context: Context,
private val lifecycle: Lifecycle,
private val callback: (Location) -> Unit
) {
private var enabled = false
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun start() {
if (enabled) {
// connect
}
}
fun enable() {
enabled = true
if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
// connect if not connected
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stop() {
// disconnect if connected
}
}
LifeCycle Events and States
Fragment View Lifecycle (ViewModel)
viewModel.plantAndGardenPlantings.observe(viewLifecycleOwner, Observer { result ->

if (result != null && result.isNotEmpty())

adapter.submitList(result)

})
LifeCycle Benefits
! Avoid Lifecycle related UI state loss: View Model
! Observability for your UI: LiveData
! Avoid Lifecycle related memory leak
! LiveData transformations
! UI-Database observations : LiveData /Room
! XML-ViewModel observations: DataBinding
! Query and Observe UI Lifecycle State
Use cases for lifecycle-aware components
! Switching between coarse and fine-grained location
updates.
! Stopping and starting video buffering.
! Starting and stopping network connectivity.
! Pausing and resuming animated drawables.
Databinding
Databinding
A support library that allows you to bind UI components in your
layouts to data sources in your app using a declarative format
rather than programmatically.
TextView textView = findViewById(R.id.sample_text);
textView.setText(viewModel.getUserName());
<TextView
android:text="@{viewmodel.userName}" />
Databinding 💕 LiveData
class PlantDetailViewModel() : ViewModel() {

val plant: LiveData<Plant> = ...



}

<data>

<variable

name="viewModel"

type="viewmodels.PlantAndGardenPlantingsViewModel"/>

</data>

<ImageView

android:layout_width="match_parent"

android:layout_height="100dp"

android:scaleType="centerCrop"

app:imageFromUrl="@{viewModel.imageUrl}"

/>


Databinding : One More thing
android {

dataBinding {

enabled = true

}
}
val binding = DataBindingUtil.inflate<FragmentPlantDetailBinding>(

inflater, R.layout.fragment_plant_detail, container, false).apply {

viewModel = plantDetailViewModel

setLifecycleOwner(this@PlantDetailFragment)

}
ViewModel
ViewModel
! Provide data for UI Components
! Survive Configuration changes
ViewModel
Hold UI Data
Repository
API for loading and saving
data
Activity
Drawing UI
User Interactions
Presenter
Process Data for UI
ViewModel
class PlantDetailViewModel() : ViewModel() {

val plant: LiveData<Plant>

}
override fun onCreateView(

inflater: LayoutInflater,

container: ViewGroup?,

savedInstanceState: Bundle?

): View? {

val plantDetailViewModel = ViewModelProviders.of(this, factory)

.get(PlantDetailViewModel::class.java)



}
Don’t store activity context in
ViewModel
LiveData
LiveData
LiveData is an observable data holder. It is lifecycle aware
public class ProductViewModel extends AndroidViewModel {

private final LiveData<ProductEntity> mObservableProduct;

// ....

public LiveData<ProductEntity> getObservableProduct() {

return mObservableProduct;

}
}
// Observe product data and
model.getObservableProduct().observe(this, new Observer<ProductEntity>() {

@Override

public void onChanged(@Nullable ProductEntity productEntity) {

// update UI

}

});
ViewModel + LiveData +
DataBinding = Reactive UI
Room
Room
! Object Mapping for SQLite Database
! Raw Queries are supported
! Support for RxJava
! Work with java.util.Optional
Room - Entity
@Entity(tableName = "plants")

data class Plant(

@PrimaryKey @ColumnInfo(name = "id") val plantId: String,

val name: String,

val description: String,

val growZoneNumber: Int,

val wateringInterval: Int = 7,

val imageUrl: String = ""

)
Room - Dao
@Dao

interface PlantDao {

@Query("SELECT * FROM plants ORDER BY name")

fun getPlants(): LiveData<List<Plant>>

@Query("SELECT * FROM plants WHERE growZoneNumber = :growZoneNumber ORDER BY name")

fun getPlantsWithGrowZoneNumber(growZoneNumber: Int): LiveData<List<Plant>>

@Query("SELECT * FROM plants WHERE id = :plantId")

fun getPlant(plantId: String): LiveData<Plant>

@Insert(onConflict = OnConflictStrategy.REPLACE)

fun insertAll(plants: List<Plant>)

}
Observable queries
Room - RoomDatabase
@Database(entities = [GardenPlanting::class, Plant::class], version = 1, exportSchema = false)

@TypeConverters(Converters::class)

abstract class AppDatabase : RoomDatabase() {

abstract fun gardenPlantingDao(): GardenPlantingDao

abstract fun plantDao(): PlantDao



...

}
Modern Android App
Architecture
Paging Library
Paging
! Fetch from database, Network, or both into RecycleView
! Extension of observable List Pattern (e.g LiveData<List>)
! Configurable Load Size, prefetch, placeholders
! Integrates with Room, LiveData, RX
! Stable release
Paging - core components 1/2
! PagedList
○ Load data in pages
○ Async data loading
! DataSource and DataSource.Factory
○ Base class for loading snapshots of data into PagedList
○ Backed by Network or Database
Paging - core components 2/2
! LivePagedListBuilder
○ Build a LiveData<PagedList> based on DataSource.Factory and
a PagedList.config
! BoundaryCallBack
○ Signals when PagedList has reached end of available data
! PagedListAdapter
○ A RecyclerView.Adapter that presents data from PagedLists
Paging - simplified
UI
PageListAdapter
PagedList
--------------
--------------
--------------
Data Layer
DataSource.Factory
BoundyCallBack
Data Source
OnItemAtEndLoaded()
Save data
Get Data
ViewModel
LiveData<PagedList>
Repository
LivePagedListBuilder
LiveData<PagedList>
create()
Build
--------------
Load
more
DataSource
! PageKeyedDataSource
! ItemKeyedDataSource
! PositionalDataSource
BoundaryCallBack
class ConcertBoundaryCallback(
private val query: String,
private val service: MyService,
private val cache: MyLocalCache
) : PagedList.BoundaryCallback<Concert>() {
override fun onZeroItemsLoaded() {
requestAndSaveData(query)
}
override fun onItemAtEndLoaded(itemAtEnd: Concert) {
requestAndSaveData(query)
}
}
Navigation
Navigation - Challenges
! Passing Arguments
! Deep Links
! Fragment Transactions
! Testing
Navigation - Only available in Android Studio 3.3
Navigation
<navigation xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:android="http://schemas.android.com/apk/res/android"

app:startDestination="@+id/garden_fragment">

<fragment

android:id="@+id/plant_list_fragment"

android:name="com.google.samples.apps.sunflower.PlantListFragment">
<argument

.../>

<action

android:id="@+id/action_plant_list_fragment_to_plant_detail_fragment"

app:destination="@id/plant_detail_fragment"

app:enterAnim="@anim/slide_in_right"

app:exitAnim="@anim/slide_out_left"

app:popEnterAnim="@anim/slide_in_left"

app:popExitAnim="@anim/slide_out_right" />

</fragment>
....

</navigation>
Navigation - Add Navgraph
<fragment

android:id="@+id/garden_nav_fragment"

android:name="androidx.navigation.fragment.NavHostFragment"

android:layout_width="match_parent"

android:layout_height="match_parent"

app:defaultNavHost="true"

app:navGraph="@navigation/nav_garden"/>
Navigation - NavigationController
val navController = Navigation.findNavController(this, R.id.garden_nav_fragment)



// Set up ActionBar

setSupportActionBar(binding.toolbar)

NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)



// Set up navigation menu

binding.navigationView.setupWithNavController(navController)
Navigation - NavigationOnClickListener
private fun createOnClickListener(plantId: String): View.OnClickListener {

val bundle = bundleOf(PlantDetailFragment.ARG_ITEM_ID to plantId)

return Navigation.createNavigateOnClickListener(

R.id.action_plant_list_fragment_to_plant_detail_fragment, bundle)

}
<action

android:id="@+id/action_plant_list_fragment_to_plant_detail_fragment"

app:destination="@id/plant_detail_fragment"/>
Navigation - CodeLab
https://codelabs.developers.google.com/codelabs/android-navigation
Adding arguments via Navigation Component : https://codelabs.developers.google.com/codelabs/android-
navigation/#7
WorkManager
! WorkManager might use JobScheduler, Firebase
JobDispatcher, or AlarmManager
! Work Manager will use best option for you!
WorkManager Basics
! Worker
! WorkRequest
! OneTimeWorkRequest
! PeriodicWorkRequest
! WorkManager
! WorkInfo
Typical Flow (Compress Images example)
class CompressWorker(context : Context, params : WorkerParameters)
: Worker(context, params) {
override fun doWork(): Result {
// Do the work here--in this case, compress the stored images.
// In this example no parameters are passed; the task is
// assumed to be "compress the whole library."
myCompress()
// Indicate success or failure with your return value:
return Result.SUCCESS
// (Returning RETRY tells WorkManager to try this task again
// later; FAILURE says not to try again.)
}
}
Typical Flow (Compress Images example)
// Create a Constraints object that defines when the task should run
val myConstraints = Constraints.Builder()
.setRequiresDeviceIdle(true)
.setRequiresCharging(true)
// Many other constraints are available, see the
// Constraints.Builder reference
.build()
// ...then create a OneTimeWorkRequest that uses those constraints
val compressionWork = OneTimeWorkRequestBuilder<CompressWorker>()
.setConstraints(myConstraints)
.build()
WorkManager.getInstance().enqueue(compressionWork)
Typical Flow - Cancelling a task
val compressionWorkId:UUID = compressionWork.getId()
WorkManager.getInstance().cancelWorkById(compressionWorkId)
Samples and Code Lab
Android SunFlower https://github.com/googlesamples/android-sunflower
Universal Music Player https://github.com/googlesamples/android-UniversalMusicPlayer/blob/master/app/build.gradle
Architecture Components https://github.com/googlesamples/android-architecture-components
Plaid 2.0 https://github.com/nickbutcher/plaid
Code Labs https://codelabs.developers.google.com/?cat=Android
Guide to Architecture Components https://developer.android.com/jetpack/docs/guide
Code Highlighter : https://romannurik.github.io/SlidesCodeHighlighter/
Conclusion
! Finally Android platform got an Architecture
! Highly Recommended for New Apps
! Try out samples and code-labs
Thank You!
Twitter : @hassanabidpk
Github : hassanabidpk

Contenu connexe

Tendances

Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFPierre-Yves Ricau
 
React Native Androidはなぜ動くのか
React Native Androidはなぜ動くのかReact Native Androidはなぜ動くのか
React Native Androidはなぜ動くのかYukiya Nakagawa
 
D2 OPEN SEMINAR - WWDC 핫 이슈
D2 OPEN SEMINAR - WWDC 핫 이슈D2 OPEN SEMINAR - WWDC 핫 이슈
D2 OPEN SEMINAR - WWDC 핫 이슈NAVER D2
 
Building cross-platform mobile apps with React Native (Jfokus 2017)
Building cross-platform mobile apps with React Native (Jfokus 2017)Building cross-platform mobile apps with React Native (Jfokus 2017)
Building cross-platform mobile apps with React Native (Jfokus 2017)Maarten Mulders
 
Dicoding Developer Coaching #30: Android | Mengenal Macam-Macam Software Desi...
Dicoding Developer Coaching #30: Android | Mengenal Macam-Macam Software Desi...Dicoding Developer Coaching #30: Android | Mengenal Macam-Macam Software Desi...
Dicoding Developer Coaching #30: Android | Mengenal Macam-Macam Software Desi...DicodingEvent
 
Web components with java by Haijian Wang
Web components with java by Haijian WangWeb components with java by Haijian Wang
Web components with java by Haijian WangGWTcon
 
High Performance NodeJS
High Performance NodeJSHigh Performance NodeJS
High Performance NodeJSDicoding
 
Using Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectUsing Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectFabio Collini
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorBartosz Kosarzycki
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSGunnar Hillert
 
Android application development the basics (2)
Android application development the basics (2)Android application development the basics (2)
Android application development the basics (2)Aliyu Olalekan
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJSGregor Woiwode
 
KOIN for dependency Injection
KOIN for dependency InjectionKOIN for dependency Injection
KOIN for dependency InjectionKirill Rozov
 

Tendances (20)

Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SF
 
Workshop 15: Ionic framework
Workshop 15: Ionic frameworkWorkshop 15: Ionic framework
Workshop 15: Ionic framework
 
React Native Androidはなぜ動くのか
React Native Androidはなぜ動くのかReact Native Androidはなぜ動くのか
React Native Androidはなぜ動くのか
 
D2 OPEN SEMINAR - WWDC 핫 이슈
D2 OPEN SEMINAR - WWDC 핫 이슈D2 OPEN SEMINAR - WWDC 핫 이슈
D2 OPEN SEMINAR - WWDC 핫 이슈
 
Building cross-platform mobile apps with React Native (Jfokus 2017)
Building cross-platform mobile apps with React Native (Jfokus 2017)Building cross-platform mobile apps with React Native (Jfokus 2017)
Building cross-platform mobile apps with React Native (Jfokus 2017)
 
Dicoding Developer Coaching #30: Android | Mengenal Macam-Macam Software Desi...
Dicoding Developer Coaching #30: Android | Mengenal Macam-Macam Software Desi...Dicoding Developer Coaching #30: Android | Mengenal Macam-Macam Software Desi...
Dicoding Developer Coaching #30: Android | Mengenal Macam-Macam Software Desi...
 
Building maintainable app
Building maintainable appBuilding maintainable app
Building maintainable app
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Stmik bandung
Stmik bandungStmik bandung
Stmik bandung
 
Web components with java by Haijian Wang
Web components with java by Haijian WangWeb components with java by Haijian Wang
Web components with java by Haijian Wang
 
High Performance NodeJS
High Performance NodeJSHigh Performance NodeJS
High Performance NodeJS
 
Using Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectUsing Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture project
 
AngularJS - TechTalk 3/2/2014
AngularJS - TechTalk 3/2/2014AngularJS - TechTalk 3/2/2014
AngularJS - TechTalk 3/2/2014
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processor
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
 
Android application development the basics (2)
Android application development the basics (2)Android application development the basics (2)
Android application development the basics (2)
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJS
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
 
KOIN for dependency Injection
KOIN for dependency InjectionKOIN for dependency Injection
KOIN for dependency Injection
 

Similaire à Building Modern Apps using Android Architecture Components

The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android JetpackAhmad Arif Faizin
 
Android Architecture Components with Kotlin
Android Architecture Components with KotlinAndroid Architecture Components with Kotlin
Android Architecture Components with KotlinAdit Lal
 
Android Jetpack - Google IO Extended Singapore 2018
Android Jetpack - Google IO Extended Singapore 2018Android Jetpack - Google IO Extended Singapore 2018
Android Jetpack - Google IO Extended Singapore 2018Hassan Abid
 
07_UIAndroid.pdf
07_UIAndroid.pdf07_UIAndroid.pdf
07_UIAndroid.pdfImranS18
 
Android development for iOS developers
Android development for iOS developersAndroid development for iOS developers
Android development for iOS developersDarryl Bayliss
 
android design pattern
android design patternandroid design pattern
android design patternLucas Xu
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WAREFermin Galan
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsMatteo Manchi
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)Jose Manuel Pereira Garcia
 
Cross-Platform Native Mobile Development with Eclipse
Cross-Platform Native Mobile Development with EclipseCross-Platform Native Mobile Development with Eclipse
Cross-Platform Native Mobile Development with EclipsePeter Friese
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT TalkConstantine Mars
 
Architecture Components
Architecture Components Architecture Components
Architecture Components DataArt
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recieversUtkarsh Mankad
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Murat Yener
 
Cleaning your architecture with android architecture components
Cleaning your architecture with android architecture componentsCleaning your architecture with android architecture components
Cleaning your architecture with android architecture componentsDebora Gomez Bertoli
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWAREFIWARE
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client TechnologyRed Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client TechnologyMark Proctor
 
Android development with Scala and SBT
Android development with Scala and SBTAndroid development with Scala and SBT
Android development with Scala and SBTAnton Yalyshev
 

Similaire à Building Modern Apps using Android Architecture Components (20)

The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android Jetpack
 
Android Architecture Components with Kotlin
Android Architecture Components with KotlinAndroid Architecture Components with Kotlin
Android Architecture Components with Kotlin
 
Android Jetpack - Google IO Extended Singapore 2018
Android Jetpack - Google IO Extended Singapore 2018Android Jetpack - Google IO Extended Singapore 2018
Android Jetpack - Google IO Extended Singapore 2018
 
07_UIAndroid.pdf
07_UIAndroid.pdf07_UIAndroid.pdf
07_UIAndroid.pdf
 
Android development for iOS developers
Android development for iOS developersAndroid development for iOS developers
Android development for iOS developers
 
android design pattern
android design patternandroid design pattern
android design pattern
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WARE
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Cross-Platform Native Mobile Development with Eclipse
Cross-Platform Native Mobile Development with EclipseCross-Platform Native Mobile Development with Eclipse
Cross-Platform Native Mobile Development with Eclipse
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT Talk
 
Architecture Components
Architecture Components Architecture Components
Architecture Components
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
Green dao
Green daoGreen dao
Green dao
 
Cleaning your architecture with android architecture components
Cleaning your architecture with android architecture componentsCleaning your architecture with android architecture components
Cleaning your architecture with android architecture components
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client TechnologyRed Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
 
Android development with Scala and SBT
Android development with Scala and SBTAndroid development with Scala and SBT
Android development with Scala and SBT
 

Plus de Hassan Abid

Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesHassan Abid
 
Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)Hassan Abid
 
Kotlin for Android Developers
Kotlin for Android DevelopersKotlin for Android Developers
Kotlin for Android DevelopersHassan Abid
 
What's new in Android Pie
What's new in Android PieWhat's new in Android Pie
What's new in Android PieHassan Abid
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applicationsHassan Abid
 
VR Video Apps on Daydream
VR Video Apps on DaydreamVR Video Apps on Daydream
VR Video Apps on DaydreamHassan Abid
 
Best Practices in Media Playback
Best Practices in Media PlaybackBest Practices in Media Playback
Best Practices in Media PlaybackHassan Abid
 
ExoPlayer for Application developers
ExoPlayer for Application developersExoPlayer for Application developers
ExoPlayer for Application developersHassan Abid
 
Android n preview
Android n previewAndroid n preview
Android n previewHassan Abid
 
Introduction to Pakistan
Introduction to PakistanIntroduction to Pakistan
Introduction to PakistanHassan Abid
 

Plus de Hassan Abid (10)

Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
 
Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)
 
Kotlin for Android Developers
Kotlin for Android DevelopersKotlin for Android Developers
Kotlin for Android Developers
 
What's new in Android Pie
What's new in Android PieWhat's new in Android Pie
What's new in Android Pie
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applications
 
VR Video Apps on Daydream
VR Video Apps on DaydreamVR Video Apps on Daydream
VR Video Apps on Daydream
 
Best Practices in Media Playback
Best Practices in Media PlaybackBest Practices in Media Playback
Best Practices in Media Playback
 
ExoPlayer for Application developers
ExoPlayer for Application developersExoPlayer for Application developers
ExoPlayer for Application developers
 
Android n preview
Android n previewAndroid n preview
Android n preview
 
Introduction to Pakistan
Introduction to PakistanIntroduction to Pakistan
Introduction to Pakistan
 

Dernier

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 

Dernier (20)

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 

Building Modern Apps using Android Architecture Components

  • 1. Building Modern Apps using Android Architecture Components Hassan Abid GDE Android - Singapore @hassanabidpk
  • 2.
  • 3. Google I/O Talks ! Android Jetpack: what's new in Android Support Library ! Android Jetpack: what's new in Architecture Components ! Modern Android development: Android Jetpack, Kotlin, and more ! Android Jetpack: how to smartly use Fragments in your UI ! Android Jetpack: manage UI navigation with Navigation Controller ! Android Jetpack: manage infinite lists with RecyclerView and Paging ! Android Jetpack: easy background processing with WorkManager ! Android Slices: build interactive results for Google Search ! Android Jetpack: sweetening Kotlin development with Android KTX ! Protips: a fresh look at advanced topics for Android experts
  • 4. Android Dev Summit 2018 Talks ! https://www.youtube.com/playlist?list=PLWz5rJ2EKKc8WFYCR9esqGGY0vOZm2l6e
  • 5. AndroidX : Android Extension Libraries ! AndroidX fully replaces the Support Library by providing feature parity and new libraries ! Added to Android Open Source Project
  • 6. AndroidX AndroidX: "Android Extension Libraries" android.support.v4.view.ViewCompat → androidx.core.view.ViewCompat android.support.v7.app.AppCompatActivity → androidx.appcompat.app.AppCompatActivity android.arch.persistence.room.RoomDatabase → androidx.room.RoomDatabase
  • 7. AndroidX ! Strict Semantic versioning rule ○ Reset to 1.0.0
  • 10. Architecture Components ! LifeCycle (2.0.0 Stable) ! Data-binding (Stable, 3.2 New!) ! ViewModel (Stable, New!) ! LiveData (Stable, New!) ! Room (2.1 New!) ! Paging (2.1 New) ! WorkManager (New!) ! Navigation (New!) https://developer.android.com/jetpack/docs/release-notes
  • 11. Adding Components to your project allprojects { repositories { jcenter() google() } }
  • 12. Example : LifeCycle - include ViewModel and LiveData (Pre-AndroidX) dependencies { def lifecycle_version = “2.0.0“ // ViewModel and LiveData implementation "android.arch.lifecycle:extensions:$lifecycle_version" // alternatively - just ViewModel. use -ktx for Kotlin implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" }
  • 13. Example : LifeCycle (AndroidX) dependencies { def lifecycle_version = "2.0.0" // ViewModel and LiveData implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version" // alternatively - just ViewModel use -ktx for Kotlin implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version" }
  • 16. LifeCycle Problem internal class MyLocationListener( private val context: Context, private val callback: (Location) -> Unit ) { fun start() { // connect to system location service } fun stop() { // disconnect from system location service } }
  • 17. LifeCycle Problem class MyActivity : AppCompatActivity() { private lateinit var myLocationListener: MyLocationListener override fun onCreate(...) { myLocationListener = MyLocationListener(this) { location -> // update UI } } public override fun onStart() { super.onStart() myLocationListener.start() // manage other components that need to respond // to the activity lifecycle } public override fun onStop() { super.onStop() myLocationListener.stop() // manage other components that need to respond // to the activity lifecycle } }
  • 18. Solution ! LifeCycle Owners : Objects with LifeCycle like Activities and Fragments ! LifeCycle Observers : Observe Lifecycle owners and are notified life cycle changes
  • 19. Solution class MyActivity : AppCompatActivity() { private lateinit var myLocationListener: MyLocationListener override fun onCreate(...) { myLocationListener = MyLocationListener(this, lifecycle) { location -> // update UI } Util.checkUserStatus { result -> if (result) { myLocationListener.enable() } } } }
  • 20. Solution internal class MyLocationListener( private val context: Context, private val lifecycle: Lifecycle, private val callback: (Location) -> Unit ) { private var enabled = false @OnLifecycleEvent(Lifecycle.Event.ON_START) fun start() { if (enabled) { // connect } } fun enable() { enabled = true if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) { // connect if not connected } } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun stop() { // disconnect if connected } }
  • 22. Fragment View Lifecycle (ViewModel) viewModel.plantAndGardenPlantings.observe(viewLifecycleOwner, Observer { result ->
 if (result != null && result.isNotEmpty())
 adapter.submitList(result)
 })
  • 23. LifeCycle Benefits ! Avoid Lifecycle related UI state loss: View Model ! Observability for your UI: LiveData ! Avoid Lifecycle related memory leak ! LiveData transformations ! UI-Database observations : LiveData /Room ! XML-ViewModel observations: DataBinding ! Query and Observe UI Lifecycle State
  • 24. Use cases for lifecycle-aware components ! Switching between coarse and fine-grained location updates. ! Stopping and starting video buffering. ! Starting and stopping network connectivity. ! Pausing and resuming animated drawables.
  • 26. Databinding A support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. TextView textView = findViewById(R.id.sample_text); textView.setText(viewModel.getUserName()); <TextView android:text="@{viewmodel.userName}" />
  • 27. Databinding 💕 LiveData class PlantDetailViewModel() : ViewModel() {
 val plant: LiveData<Plant> = ...
 
 }
 <data>
 <variable
 name="viewModel"
 type="viewmodels.PlantAndGardenPlantingsViewModel"/>
 </data>
 <ImageView
 android:layout_width="match_parent"
 android:layout_height="100dp"
 android:scaleType="centerCrop"
 app:imageFromUrl="@{viewModel.imageUrl}"
 /> 

  • 28. Databinding : One More thing android {
 dataBinding {
 enabled = true
 } } val binding = DataBindingUtil.inflate<FragmentPlantDetailBinding>(
 inflater, R.layout.fragment_plant_detail, container, false).apply {
 viewModel = plantDetailViewModel
 setLifecycleOwner(this@PlantDetailFragment)
 }
  • 30. ViewModel ! Provide data for UI Components ! Survive Configuration changes ViewModel Hold UI Data Repository API for loading and saving data Activity Drawing UI User Interactions Presenter Process Data for UI
  • 31. ViewModel class PlantDetailViewModel() : ViewModel() {
 val plant: LiveData<Plant>
 } override fun onCreateView(
 inflater: LayoutInflater,
 container: ViewGroup?,
 savedInstanceState: Bundle?
 ): View? {
 val plantDetailViewModel = ViewModelProviders.of(this, factory)
 .get(PlantDetailViewModel::class.java)
 
 } Don’t store activity context in ViewModel
  • 33. LiveData LiveData is an observable data holder. It is lifecycle aware public class ProductViewModel extends AndroidViewModel {
 private final LiveData<ProductEntity> mObservableProduct;
 // ....
 public LiveData<ProductEntity> getObservableProduct() {
 return mObservableProduct;
 } } // Observe product data and model.getObservableProduct().observe(this, new Observer<ProductEntity>() {
 @Override
 public void onChanged(@Nullable ProductEntity productEntity) {
 // update UI
 }
 });
  • 34. ViewModel + LiveData + DataBinding = Reactive UI
  • 35. Room
  • 36. Room ! Object Mapping for SQLite Database ! Raw Queries are supported ! Support for RxJava ! Work with java.util.Optional
  • 37. Room - Entity @Entity(tableName = "plants")
 data class Plant(
 @PrimaryKey @ColumnInfo(name = "id") val plantId: String,
 val name: String,
 val description: String,
 val growZoneNumber: Int,
 val wateringInterval: Int = 7,
 val imageUrl: String = ""
 )
  • 38. Room - Dao @Dao
 interface PlantDao {
 @Query("SELECT * FROM plants ORDER BY name")
 fun getPlants(): LiveData<List<Plant>>
 @Query("SELECT * FROM plants WHERE growZoneNumber = :growZoneNumber ORDER BY name")
 fun getPlantsWithGrowZoneNumber(growZoneNumber: Int): LiveData<List<Plant>>
 @Query("SELECT * FROM plants WHERE id = :plantId")
 fun getPlant(plantId: String): LiveData<Plant>
 @Insert(onConflict = OnConflictStrategy.REPLACE)
 fun insertAll(plants: List<Plant>)
 } Observable queries
  • 39. Room - RoomDatabase @Database(entities = [GardenPlanting::class, Plant::class], version = 1, exportSchema = false)
 @TypeConverters(Converters::class)
 abstract class AppDatabase : RoomDatabase() {
 abstract fun gardenPlantingDao(): GardenPlantingDao
 abstract fun plantDao(): PlantDao
 
 ...
 }
  • 41.
  • 43. Paging ! Fetch from database, Network, or both into RecycleView ! Extension of observable List Pattern (e.g LiveData<List>) ! Configurable Load Size, prefetch, placeholders ! Integrates with Room, LiveData, RX ! Stable release
  • 44. Paging - core components 1/2 ! PagedList ○ Load data in pages ○ Async data loading ! DataSource and DataSource.Factory ○ Base class for loading snapshots of data into PagedList ○ Backed by Network or Database
  • 45. Paging - core components 2/2 ! LivePagedListBuilder ○ Build a LiveData<PagedList> based on DataSource.Factory and a PagedList.config ! BoundaryCallBack ○ Signals when PagedList has reached end of available data ! PagedListAdapter ○ A RecyclerView.Adapter that presents data from PagedLists
  • 46. Paging - simplified UI PageListAdapter PagedList -------------- -------------- -------------- Data Layer DataSource.Factory BoundyCallBack Data Source OnItemAtEndLoaded() Save data Get Data ViewModel LiveData<PagedList> Repository LivePagedListBuilder LiveData<PagedList> create() Build -------------- Load more
  • 48. BoundaryCallBack class ConcertBoundaryCallback( private val query: String, private val service: MyService, private val cache: MyLocalCache ) : PagedList.BoundaryCallback<Concert>() { override fun onZeroItemsLoaded() { requestAndSaveData(query) } override fun onItemAtEndLoaded(itemAtEnd: Concert) { requestAndSaveData(query) } }
  • 50. Navigation - Challenges ! Passing Arguments ! Deep Links ! Fragment Transactions ! Testing
  • 51. Navigation - Only available in Android Studio 3.3
  • 53. Navigation - Add Navgraph <fragment
 android:id="@+id/garden_nav_fragment"
 android:name="androidx.navigation.fragment.NavHostFragment"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 app:defaultNavHost="true"
 app:navGraph="@navigation/nav_garden"/>
  • 54. Navigation - NavigationController val navController = Navigation.findNavController(this, R.id.garden_nav_fragment)
 
 // Set up ActionBar
 setSupportActionBar(binding.toolbar)
 NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)
 
 // Set up navigation menu
 binding.navigationView.setupWithNavController(navController)
  • 55. Navigation - NavigationOnClickListener private fun createOnClickListener(plantId: String): View.OnClickListener {
 val bundle = bundleOf(PlantDetailFragment.ARG_ITEM_ID to plantId)
 return Navigation.createNavigateOnClickListener(
 R.id.action_plant_list_fragment_to_plant_detail_fragment, bundle)
 } <action
 android:id="@+id/action_plant_list_fragment_to_plant_detail_fragment"
 app:destination="@id/plant_detail_fragment"/>
  • 56. Navigation - CodeLab https://codelabs.developers.google.com/codelabs/android-navigation Adding arguments via Navigation Component : https://codelabs.developers.google.com/codelabs/android- navigation/#7
  • 57. WorkManager ! WorkManager might use JobScheduler, Firebase JobDispatcher, or AlarmManager ! Work Manager will use best option for you!
  • 58. WorkManager Basics ! Worker ! WorkRequest ! OneTimeWorkRequest ! PeriodicWorkRequest ! WorkManager ! WorkInfo
  • 59. Typical Flow (Compress Images example) class CompressWorker(context : Context, params : WorkerParameters) : Worker(context, params) { override fun doWork(): Result { // Do the work here--in this case, compress the stored images. // In this example no parameters are passed; the task is // assumed to be "compress the whole library." myCompress() // Indicate success or failure with your return value: return Result.SUCCESS // (Returning RETRY tells WorkManager to try this task again // later; FAILURE says not to try again.) } }
  • 60. Typical Flow (Compress Images example) // Create a Constraints object that defines when the task should run val myConstraints = Constraints.Builder() .setRequiresDeviceIdle(true) .setRequiresCharging(true) // Many other constraints are available, see the // Constraints.Builder reference .build() // ...then create a OneTimeWorkRequest that uses those constraints val compressionWork = OneTimeWorkRequestBuilder<CompressWorker>() .setConstraints(myConstraints) .build() WorkManager.getInstance().enqueue(compressionWork)
  • 61. Typical Flow - Cancelling a task val compressionWorkId:UUID = compressionWork.getId() WorkManager.getInstance().cancelWorkById(compressionWorkId)
  • 62. Samples and Code Lab Android SunFlower https://github.com/googlesamples/android-sunflower Universal Music Player https://github.com/googlesamples/android-UniversalMusicPlayer/blob/master/app/build.gradle Architecture Components https://github.com/googlesamples/android-architecture-components Plaid 2.0 https://github.com/nickbutcher/plaid Code Labs https://codelabs.developers.google.com/?cat=Android Guide to Architecture Components https://developer.android.com/jetpack/docs/guide Code Highlighter : https://romannurik.github.io/SlidesCodeHighlighter/
  • 63. Conclusion ! Finally Android platform got an Architecture ! Highly Recommended for New Apps ! Try out samples and code-labs
  • 64. Thank You! Twitter : @hassanabidpk Github : hassanabidpk