0% found this document useful (0 votes)
107 views33 pages

Lesson 12 Repository Pattern and WorkManager

This document discusses the repository pattern and WorkManager in Android development. It describes the repository pattern as abstracting away multiple data sources to allow for fast retrieval from local storage while fetching new data from network sources. It also explains that WorkManager is the recommended solution for executing background work in Android, and that it allows work to be scheduled immediately or deferred under certain constraints. Key aspects covered include defining Workers, creating WorkRequests, providing work input and output, and setting constraints on when WorkRequests can run.

Uploaded by

ravej39354
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
107 views33 pages

Lesson 12 Repository Pattern and WorkManager

This document discusses the repository pattern and WorkManager in Android development. It describes the repository pattern as abstracting away multiple data sources to allow for fast retrieval from local storage while fetching new data from network sources. It also explains that WorkManager is the recommended solution for executing background work in Android, and that it allows work to be scheduled immediately or deferred under certain constraints. Key aspects covered include defining Workers, creating WorkRequests, providing work input and output, and setting constraints on when WorkRequests can run.

Uploaded by

ravej39354
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 33

Lesson 12:

Repository pattern
and WorkManager

Android Development with Kotlin v1.0 This work is licensed under the Apache 2 license. 1
About this lesson
Lesson 12: Repository pattern and WorkManager
● Repository pattern
● WorkManager
● Work input and output
● WorkRequest constraints
● Summary

Android Development with Kotlin This work is licensed under the Apache 2 license. 2
Repository pattern

Android Development with Kotlin This work is licensed under the Apache 2 license. 3
Existing app architecture

UI Controller

ViewModel

Room

Android Development with Kotlin This work is licensed under the Apache 2 license. 4
Relative data speeds

Operation Relative speed

Reading from LiveData FAST

Reading from Room database SLOW

Reading from network SLOWEST

Android Development with Kotlin This work is licensed under the Apache 2 license. 5
Cache network responses

● Account for long network request times and still be responsive


to the user
● Use Room locally when retrieval from the network may be costly
or difficult
● Can cache based on the least recently used (LRU) value,
frequently accessed (FRU) values, or other algorithm

Android Development with Kotlin This work is licensed under the Apache 2 license. 6
Repository pattern

● Can abstract away multiple data sources from the caller


● Supports fast retrieval using local database while sending
network request for data refresh (which can take longer)
● Can test data sources separately from other aspects of your app

Android Development with Kotlin This work is licensed under the Apache 2 license. 7
App architecture with repository pattern
UI Controller

ViewModel

Repository

Remote data source Room Mock backend

Android Development with Kotlin This work is licensed under the Apache 2 license. 8
Implement a repository class

● Provide a common interface to access data:


○ Expose functions to query and modify the underlying data
● Depending on your data sources, the repository can:
○ Hold a reference to the DAO, if your data is in a database
○ Make network requests if you connect to a web service

Android Development with Kotlin This work is licensed under the Apache 2 license. 9
WorkManager

Android Development with Kotlin This work is licensed under the Apache 2 license. 10
WorkManager

● Android Jetpack architecture component


● Recommended solution to execute background work
(immediate or deferred)
● Opportunistic and guaranteed execution
● Execution can be based on certain conditions

Android Development with Kotlin This work is licensed under the Apache 2 license. 11
When to use WorkManager

Task

Yes Requires active No


user

Requires active
Immediate user
Yes No

Exact Deferred

Android Development with Kotlin This work is licensed under the Apache 2 license. 12
Declare WorkManager dependencies

implementation "androidx.work:work-runtime-ktx:$work_version"

Android Development with Kotlin This work is licensed under the Apache 2 license. 13
Important classes to know

● Worker - does the work on a background thread, override


doWork() method
● WorkRequest - request to do some work
● Constraint - conditions on when the work can run
● WorkManager - schedules the WorkRequest to be run

Android Development with Kotlin This work is licensed under the Apache 2 license. 14
Define the work
class UploadWorker(appContext: Context, workerParams: WorkerParameters) :
Worker(appContext, workerParams) {

override fun doWork(): Result {

// Do the work here. In this case, upload the images.


uploadImages()

// Indicate whether work finished successfully with the Result


return Result.success()
}
}

Android Development with Kotlin This work is licensed under the Apache 2 license. 15
Extend CoroutineWorker instead of Worker
class UploadWorker(appContext: Context, workerParams: WorkerParameters) :
CoroutineWorker(appContext, workerParams) {

override suspend fun doWork(): Result {

// Do the work here (in this case, upload the images)


uploadImages()

// Indicate whether work finished successfully with the Result


return Result.success()
}
}

Android Development with Kotlin This work is licensed under the Apache 2 license. 16
WorkRequests

● Can be scheduled to run once or repeatedly


○ OneTimeWorkRequest
○ PeriodicWorkRequest
● Persisted across device reboots
● Can be chained to run sequentially or in parallel
● Can have constraints under which they will run

Android Development with Kotlin This work is licensed under the Apache 2 license. 17
Schedule a OneTimeWorkRequest
Create WorkRequest:
val uploadWorkRequest: WorkRequest =
OneTimeWorkRequestBuilder<UploadWorker>()
.build()

Add the work to the WorkManager queue:

WorkManager.getInstance(myContext)
.enqueue(uploadWorkRequest)

Android Development with Kotlin This work is licensed under the Apache 2 license. 18
Schedule a PeriodicWorkRequest
● Set a repeat interval
● Set a flex interval (optional)
Flex period Flex period Flex period
can run work can run work can run work

...
Interval 1 Interval 2 Interval N

Specify an interval using TimeUnit (e.g., TimeUnit.HOURS, TimeUnit.DAYS)

Android Development with Kotlin This work is licensed under the Apache 2 license. 19
Flex interval
Work could And then again
happen here soon after

Example 1

Day 1 Day 2

1 hr 1 hr

Example 2
11 PM 12 AM 11 PM 12 AM
Day 1 Day 2

Android Development with Kotlin This work is licensed under the Apache 2 license. 20
PeriodicWorkRequest example

val repeatingRequest = PeriodicWorkRequestBuilder<RefreshDataWorker>(


1, TimeUnit.HOURS, // repeatInterval
15, TimeUnit.MINUTES // flexInterval
).build()

Android Development with Kotlin This work is licensed under the Apache 2 license. 21
Enqueue periodic work

WorkManager.getInstance().enqueueUniquePeriodicWork(
"Unique Name",
ExistingPeriodicWorkPolicy.KEEP, // or REPLACE
repeatingRequest
)

Android Development with Kotlin This work is licensed under the Apache 2 license. 22
Work input and output

Android Development with Kotlin This work is licensed under the Apache 2 license. 23
Define Worker with input and output
class MathWorker(context: Context, params: WorkerParameters):
CoroutineWorker(context, params) {

override suspend fun doWork(): Result {


val x = inputData.getInt(KEY_X_ARG, 0)
val y = inputData.getInt(KEY_Y_ARG, 0)
val result = computeMathFunction(x, y)
val output: Data = workDataOf(KEY_RESULT to result)
return Result.success(output)
}
}

Android Development with Kotlin This work is licensed under the Apache 2 license. 24
Result output from doWork()

Result status Result status with output

Result.success() Result.success(output)

Result.failure() Result.failure(output)

Result.retry()

Android Development with Kotlin This work is licensed under the Apache 2 license. 25
Send input data to Worker

val complexMathWork = OneTimeWorkRequest<MathWorker>()


.setInputData(
workDataOf(
"X_ARG" to 42,
"Y_ARG" to 421,
)
).build()

WorkManager.getInstance(myContext).enqueue(complexMathWork)

Android Development with Kotlin This work is licensed under the Apache 2 license. 26
WorkRequest constraints

Android Development with Kotlin This work is licensed under the Apache 2 license. 27
Constraints

● setRequiredNetworkType
● setRequiresBatteryNotLow
● setRequiresCharging
● setTriggerContentMaxDelay
● requiresDeviceIdle

Android Development with Kotlin This work is licensed under the Apache 2 license. 28
Constraints example
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresCharging(true)
.setRequiresBatteryNotLow(true)
.setRequiresDeviceIdle(true)
.build()

val myWorkRequest: WorkRequest = OneTimeWorkRequestBuilder<MyWork>()


.setConstraints(constraints)
.build()

Android Development with Kotlin This work is licensed under the Apache 2 license. 29
Summary

Android Development with Kotlin This work is licensed under the Apache 2 license. 30
Summary
In Lesson 12, you learned how to:
● Use a repository to abstract the data layer from the rest of the app
● Schedule background tasks efficiently and optimize them using
WorkManager
● Create custom Worker classes to specify the work to be done
● Create and enqueue one-time or periodic work requests

Android Development with Kotlin This work is licensed under the Apache 2 license. 31
Learn more

● Fetch data
● Schedule tasks with WorkManager
● Define work requests
● Connect ViewModel and the repository
● Use WorkManager for immediate background execution

Android Development with Kotlin This work is licensed under the Apache 2 license. 32
Pathway

Practice what you’ve learned by


completing the pathway:
Lesson 12: Repository pattern andWorkManager

Android Development with Kotlin This work is licensed under the Apache 2 license. 33

You might also like