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 )
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() } } }
Diversamente da Worker, questo codice non viene eseguito sull'Executor specificato nella configurazione di WorkManager.
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
Raramente è necessario cambiare il Dispatcher che CoroutineWorker sta usando e Dispatchers.Default è una buona opzione per la maggior parte dei casi.
@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())) } }
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()
assertThat(result, `is`(Result.failure())) }