Slide 1

Slide 1 text

GDG Location Handling Periodic token refresh using WorkManager Nsikak Thompson @hinsikak

Slide 2

Slide 2 text

2019 | Confidential and Proprietary GDG Location About me ● I am mobile developer currently leading mobile teams at StarthubTech & AltaLabs. ● Co-lead GDG Uyo ● A beginner Flutter Developer

Slide 3

Slide 3 text

GDG Location Have you ever had a reason to handle a task in the background ?

Slide 4

Slide 4 text

GDG Location If yes? What library or API did you use?

Slide 5

Slide 5 text

GDG Location Anyone familiar with WorkManager ?

Slide 6

Slide 6 text

GDG Location Most mobile apps use token based authentication as a security technique to authenticates the users who attempt to log in to a server through the app.

Slide 7

Slide 7 text

GDG Minna Every user token has an expiration period(this is defined by the backend auth system), therefore the user cannot access the server with an expired token

Slide 8

Slide 8 text

GDG Minna No user is happy to see this

Slide 9

Slide 9 text

2019 | Confidential and Proprietary GDG Location Scope What is WorkManager? Setup WorkManager Create a WorkRequest Schedule token update Check for expired token at app launch or Resume

Slide 10

Slide 10 text

GDG Location WorkManager is an Android library that runs deferrable background work when the work’s constraints are satisfied. WorkManager is an API part of the Android Jetpack Library. - Work constraints - Task scheduling - Work Chain What is WorkManager

Slide 11

Slide 11 text

GDG Location compatibility back to API level 14 What is WorkManager

Slide 12

Slide 12 text

GDG Location Worker Class - Work is defined using the Worker class. The doWork() method is run synchronously on a background thread provided by WorkManager. WorkManager Concepts Results - This is the status of work returned by the doWork() method. ● Result.success(): The work finished successfully. ● Result.failure(): The work failed. ● Result.retry(): The work failed and should be tried at another time according to its retry policy.

Slide 13

Slide 13 text

GDG Location WorkRequest - define how and when it should be run. 1. OneTimeWorkRequest 2. PeriodicWorkRequest WorkManager Concepts

Slide 14

Slide 14 text

GDG Location First time Login Process Login The user’s token is required to make request to the server in most case. Make Other HTTP Request This is saved locally using Database or SharedPreference. Also the login time. It return the users information which include the token and refresh Token. This token expires after 60 mins Login Successful Email and Password Save User details 1 2 3 4

Slide 15

Slide 15 text

GDG Location Add these dependencies to your build.gradle file Set up WorkManager dependencies { def work_version = "2.1.0" // (Java only) implementation "androidx.work:work-runtime:$work_version" // Kotlin + coroutines implementation "androidx.work:work-runtime-ktx:$work_version" } https://developer.android.com/jetpack/androidx/releases/work

Slide 16

Slide 16 text

GDG Location Create a class that will extend the Worker class passing in context and the workerParams. Create Token Worker class TokenWorker constructor(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { override fun doWork(): Result { //Handle your work here return result!! } }

Slide 17

Slide 17 text

GDG Location Add the logic to perform the token refresh in the doWork() method. Add Refresh Token work override fun doWork(): Result { AndroidWorkerInjection.inject(this) if (preferenceHelper.isLoggedIn) { disposable = appCache.getUserInfo() //call the api to refresh the token .flatMapCompletable {userDataStore.refreshToken( RefreshToken.Params(it.email, it.refreshToken))} .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread())

Slide 18

Slide 18 text

GDG Location The Result returned from doWork() informs WorkManager whether the task: - finished successfully via Result.success() - failed via Result.failure() Subscribe for Results ……. .subscribe ({ result = Result.success() Timber.e("Token refresh was successful") }, {error -> result = Result.failure() Timber.e("Token refresh failed") }) } return result!! }

Slide 19

Slide 19 text

GDG Location Using PeriodicWorkRequest to schedule the token refresh task to run after every 50 minutes. Remember the token validity period is 60 minutes, so we are trying to update the token before it actually expires. This helps us keep our user covered Create WorkRequest fun startTokenRefreshPeriodicWork() { val tokenRefreshBuilder = PeriodicWorkRequest.Builder( TokenWorker::class.java, 50, TimeUnit.MINUTES )

Slide 20

Slide 20 text

GDG Location The work is also given constraints that tells the work to only execute the device is connected to a Network. Add Constraints //This defines the job constraints. val tokenRefreshConstraint = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val tokenRefreshWork = tokenRefreshBuilder .addTag("TOKEN_REFRESH") .setConstraints(tokenRefreshConstraint) .build() }

Slide 21

Slide 21 text

GDG Location Once the user login is successful, the WorkManager will schedule the job. Schedule token update WorkManager.getInstance().enqueue(tokenRefreshWork)

Slide 22

Slide 22 text

GDG Location Token refresh for already Logged in user Request Token refresh The new active token will be available for the user Make HTTP Request The server returns a new token and a refresh token Request Successful The workmanager request for the a new token at the scheduled time Update Local storage 1 2 3 4

Slide 23

Slide 23 text

GDG Location WorkManager Documentation https://developer.android.com/topic/libraries/architecture/workmanager Working with WorkManager (Android Dev Summit '18) https://www.youtube.com/watch?v=83a4rYXsDs0 Resources

Slide 24

Slide 24 text

GDG Location Thank you @hinsikak