Home > Software engineering >  Compose WorkManager not getting triggered
Compose WorkManager not getting triggered

Time:01-27

I have an app that uses a Worker to update its services via the internet.

However, the worker is not getting triggered.

Worker.kt:

class MyWorker(
    private val container: AppContainer,
    ctx: Context,
    params: WorkerParameters
) : CoroutineWorker(ctx, params) {


    override suspend fun doWork(): Result {

        return withContext(Dispatchers.IO) {
            return@withContext try {

                val response = container.onlineRepository.getData()

                // Load the data
                container.offlineRepository.load(
                    data = response.data
                )

                Result.success()

            } catch (throwable: Throwable) {
                Log.e(
                    TAG, throwable.message, throwable
                )
                Result.failure()
            }
        }
    }
}

DataActivity.kt:

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val worker = OneTimeWorkRequestBuilder<MyWorker>().build()
        WorkManager.getInstance(this).enqueue(worker)

        setContent {
            DataApp()
        }
    }

When i check the logs, nothing is being logged because it is not entering the doWork()

Can someone please help ?

CodePudding user response:

In yourMyWorker class constructor, you are requiring thecontainer: AppContainer argument which is not supplied on instantiation. It's better to use WorkerParameters to achieve this.

You could use this:

// Passing params
Data.Builder data = new Data.Builder();
data.putString("my_key", my_string);

val worker = OneTimeWorkRequestBuilder<MyWorker>()
.setInputData(data.build())
.build()

WorkManager.getInstance(this).enqueue(worker)

However, WorkManager's Data class only accepts some specific types as values as explained in the reference documentation.

On top of that, there's a size limit of about 10 KB, specified by the constant MAX_DATA_BYTES.

If the data is not too big, you may want to serialize it to a String and use that as inputData in your WorkRequest.

  • Related