Lesson 12:
Repository pattern
and WorkManager
This work is licensed under the
Android Development with Kotlin Apache 2 license. 1
v1.0
About this lesson
Lesson 12: Repository pattern and WorkManager
● Repository pattern
● WorkManager
● Work input and output
● WorkRequest constraints
● Summary
This work is licensed under the
Android Development with Kotlin Apache 2 license. 2
Repository pattern
This work is licensed under the
Android Development with Kotlin Apache 2 license. 3
Existing app architecture
UI Controller
ViewModel
Room
This work is licensed under the
Android Development with Kotlin Apache 2 license. 4
Relative data speeds
Operation Relative speed
Reading from LiveData FAST
Reading from Room database SLOW
Reading from network SLOWEST
This work is licensed under the
Android Development with Kotlin 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
This work is licensed under the
Android Development with Kotlin 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 you
app
This work is licensed under the
Android Development with Kotlin Apache 2 license. 7
App architecture with
repository pattern
UI
Controller
ViewModel
Repository
Remote data
Room Mock backend
source
This work is licensed under the
Android Development with Kotlin 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
This work is licensed under the
Android Development with Kotlin Apache 2 license. 9
WorkManager
This work is licensed under the
Android Development with Kotlin 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
This work is licensed under the
Android Development with Kotlin Apache 2 license. 11
When to use WorkManager
Task
Yes Requires No
active user
Immediat Must run at
e exact time
Yes No
Deferre
Exact
d
This work is licensed under the
Android Development with Kotlin Apache 2 license. 12
Declare WorkManager
dependencies
implementation "androidx.work:work-runtime-ktx:
$work_version"
This work is licensed under the
Android Development with Kotlin 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
This work is licensed under the
Android Development with Kotlin 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
15
Apache 2 license.
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
16
Apache 2 license.
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
This work is licensed under the
Android Development with Kotlin 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)
This work is licensed under the
Android Development with Kotlin Apache 2 license. 18
Schedule a
PeriodicWorkRequest
● Set a repeat interval
● Set a flex interval (optional)
Flex Flex Flex
..
period period period
can run can run can run
work work work
Interval 1 Interval 2 . Interval N
Specify an interval using TimeUnit (e.g., TimeUnit.HOURS, TimeUnit.DAYS)
This work is licensed under the
Android Development with Kotlin Apache 2 license. 19
Flex interval
And then
Work could
again
happen here
soon after
Example
1
Day 1 Day 2
1 hr 1 hr
Example
2 12
11 PM 12 AM 11 PM
AM
Day 1 Day 2
This work is licensed under the
Android Development with Kotlin Apache 2 license. 20
PeriodicWorkRequest example
val repeatingRequest =
PeriodicWorkRequestBuilder<RefreshDataWorker>(
1, TimeUnit.HOURS, // repeatInterval
15, TimeUnit.MINUTES // flexInterval
).build()
This work is licensed under the
Android Development with Kotlin Apache 2 license. 21
Enqueue periodic work
WorkManager.getInstance().enqueueUniquePeriodicWork(
"Unique Name",
ExistingPeriodicWorkPolicy.KEEP, // or REPLACE
repeatingRequest
)
This work is licensed under the
Android Development with Kotlin Apache 2 license. 22
Work input and
output
This work is licensed under the
Android Development with Kotlin 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)
}
}
This work is licensed under the
Android Development with Kotlin 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()
This work is licensed under the
Android Development with Kotlin 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)
This work is licensed under the
Android Development with Kotlin Apache 2 license. 26
WorkRequest
constraints
This work is licensed under the
Android Development with Kotlin Apache 2 license. 27
Constraints
● setRequiredNetworkType
● setRequiresBatteryNotLow
● setRequiresCharging
● setTriggerContentMaxDelay
● requiresDeviceIdle
This work is licensed under the
Android Development with Kotlin 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()
This work is licensed under the
Android Development with Kotlin Apache 2 license. 29
Summary
This work is licensed under the
Android Development with Kotlin Apache 2 license. 30
Summary
In Lesson 12, you learned how to:
● Use a repository to abstract the data layer from the rest of th
e app
● Schedule background tasks efficiently and optimize them usi
ng
WorkManager
● Create custom Worker classes to specify the work to be done
● Create and enqueue one-time or periodic work requests
This work is licensed under the
Android Development with Kotlin 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 exec
ution
This work is licensed under the
Android Development with Kotlin Apache 2 license. 32
Pathway
Practice what you’ve learned by
completing the pathway:
Lesson 12: Repository pattern andWorkManager
This work is licensed under the
Android Development with Kotlin Apache 2 license. 33