reixa
reixa

Reputation: 7011

WorkManager alpha10 ListenableFuture usage

I´m having some issues trying to implement the latest WorkManager-alpha10 ListenableFuture for handling process completion.

Right now I´ve the following on my JobOrganizer class

private fun enqueueDownloadWork(): ListenableFuture<Void> {
    val work = WorkManager.getInstance()
                   .beginWith(dwdTypologiesJob)
                   .then(dwdElementsJob)
                   .then(dwdAnomaliesJob)
    return work.enqueue()
}

private fun createDownloadWorkRequests() {
    dwdTypologiesJob = OneTimeWorkRequestBuilder<DWDAnomalyTypesJob>()
                .addTag("download_typologies_work")
                .build()
    dwdElementsJob = OneTimeWorkRequestBuilder<DWDElementsJob>()
                .addTag("download_elements_work")
                .build()
    dwdAnomaliesJob = OneTimeWorkRequestBuilder<DWDAnomaliesJob>()
                .addTag("download_anomalies_work")
                .build()
}

fun downloadData(): ListenableFuture<Void> {
    createDownloadWorkRequests()
    return enqueueDownloadWork()
}

And this is my call who should listen for the completion event.

val listenable = JobOrganizer.downloadData()
listenable.addListener({
    Log.d("Listenable", "Did something 1");
}, {
    Log.d("Listenable", "Did something 2");
})

I´m still missing how the Runnable and Executor works on this function. Can someone explain it?

Thanks

Upvotes: 4

Views: 4103

Answers (2)

aksh1618
aksh1618

Reputation: 2571

For ListenableFuture, Runnable is the code that you want to run on completion and Executor tells it how exactly to run that code (which thread to run it on, for instance).

This should work on Kotlin:

listenableFuture.addListener(
    { /* Runnable: Code to run */ },
    { /* Executor: How to run */ }
)

Some simple executors could be as follows:

// Run on same thread (likely to be background thread):
{ it?.run }
// Run on main thread in android:
{ Handler(Looper.getMainLooper()).post(it) }
// Run with delay on main thread in android:
{ Handler(Looper.getMainLooper()).postDelayed(it, delayMillis) }

For instance, a usage in a ViewModel could look like this:

val dataDownloaded = MutableLiveData<Boolean>()
fun beginDownload() {
    downloadData.result.addListener(
        { dataDownloaded.postValue(true) },
        { it?.run() }
    )
}

Upvotes: 4

Micha
Micha

Reputation: 394

You need to instantiate both Runnable and Executor, for instance, when you want to execute the Runnable directly and on the current thread:

.addListener(
    object:Runnable {
        override fun run() {
            Log.d("Listenable", "Did something 1");
        }
    },
    object:Executor {
        override fun execute(command: Runnable?) {
            command?.run()
        }
    }

You can find more examples on Executors on https://developer.android.com/reference/java/util/concurrent/Executor

Upvotes: 4

Related Questions