Skip to content

Using work manager along with coroutines

Devrath edited this page Jun 15, 2021 · 1 revision
  • Demonstrates how you can use WorkManager together with Coroutines.
  • When creating a subclass of CoroutineWorker instead of Worker, the doWork() function is now a suspend function which means that we can now call other suspend functions.
  • In this example, we are sending an analytics request when the user enters the screen, which is a nice use case for using WorkManager.
class WorkManagerViewModel(private val context: Context) : ViewModel() {

    fun performAnalyticsRequest() {
        val constraints =
            Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()

        val request = OneTimeWorkRequestBuilder<AnalyticsWorker>()
            .setConstraints(constraints)
            // Set a delay to not slow down other UI related requests that should run fast
            .setInitialDelay(10, TimeUnit.SECONDS)
            .addTag("analyitcs-work-request")
            .build()

        WorkManager.getInstance(context).enqueue(request)
    }
}
class AnalyticsWorker(appContext: Context, workerParameters: WorkerParameters) :
    CoroutineWorker(appContext, workerParameters) {

    private val analyticsApi = createMockAnalyticsApi()

    override suspend fun doWork(): Result {
        return try {
            analyticsApi.trackScreenOpened()
            Timber.d("Successfully tracked screen open event!")
            Result.success()
        } catch (exception: Exception) {
            Timber.e("Tracking screen open event failed!")
            Result.failure()
        }
    }

    companion object {
        fun createMockAnalyticsApi() = createMockAnalyticsApi(
            MockNetworkInterceptor()
                .mock(
                    "http://localhost/analytics/workmanager-screen-opened",
                    "true",
                    200,
                    1500
                )
        )
    }
}
Clone this wiki locally