WorkManager meets Kotlin

Pietro Maggi
Jun 12 · 5 min read
Illustration by Virginia Poltrack

WorkManager in Kotlin

More concise and idiomatic

Data myData = new Data.Builder()
.putInt(KEY_ONE_INT, aInt)
.putIntArray(KEY_ONE_INT_ARRAY, aIntArray)
.putString(KEY_ONE_STRING, aString)
.build();
inline fun workDataOf(vararg pairs: Pair<String, Any?>): Data
val data = workDataOf(
KEY_MY_INT to myIntVar,
KEY_MY_INT_ARRAY to myIntArray,
KEY_MY_STRING to myString
)

CoroutineWorker

class MyWork(context: Context, params: WorkerParameters) :
CoroutineWorker(context, params) {
override suspend fun doWork(): Result {return try {
// Do something
Result.success()
} catch (error: Throwable) {
Result.failure()
}
}
}
class MyWork(context: Context, params: WorkerParameters) :
CoroutineWorker(context, params) {
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {return try {
// Do something
Result.success()
} catch (error: Throwable) {
Result.failure()
}
}
}

Testing Worker classes

@RunWith(JUnit4::class)
class MyWorkTest {
private lateinit var context: Context
@Before
fun setup() {
context = ApplicationProvider.getApplicationContext()
}
@Test
fun testMyWork() {
// Get the ListenableWorker
val worker =
TestListenableWorkerBuilder<MyWork>(context).build()
// Run the worker synchronously
val result = worker.startWork().get()
assertThat(result, `is`(Result.success()))
}
}
class MyWork(context: Context, params: WorkerParameters) :
CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val serverUrl = inputData.getString("SERVER_URL")
return try {
// Do something with the URL
Result.success()
} catch (error: TitleRefreshError) {
if (runAttemptCount <3) {
Result.retry()
} else {
Result.failure()
}
}
}
}
@Test
fun testMyWorkRetry() {
val data = workDataOf("SERVER_URL" to "http://fake.url")
// Get the ListenableWorker with a RunAttemptCount of 2
val worker = TestListenableWorkerBuilder<MyWork>(context)
.setInputData(data)
.setRunAttemptCount(2)
.build()
// Start the work synchronously
val result = worker.startWork().get()
assertThat(result, `is`(Result.retry()))
}
@Test
fun testMyWorkFailure() {
val data = workDataOf("SERVER_URL" to "http://fake.url")
// Get the ListenableWorker with a RunAttemptCount of 3
val worker = TestListenableWorkerBuilder<MyWork>(context)
.setInputData(data)
.setRunAttemptCount(3)
.build()
// Start the work synchronously
val result = worker.startWork().get()
assertThat(result, `is`(Result.failure()))
}

Conclusion

Resources

Android Developers

The official Android Developers publication on Medium

Pietro Maggi

Written by

Android Developer Advocate @Google

Android Developers

The official Android Developers publication on Medium