Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Worker and ListenableWorker in WorkManager?

I go through this link Migrating from Firebase JobDispatcher to WorkManager ,

I found there is Worker and ListenableWorker, where to use these both? any advantage on using any one of them?

Worker :

import android.content.Context;
import androidx.work.Data;
import androidx.work.ListenableWorker.Result;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

class MyWorker extends Worker {

  public MyWorker(@NonNull Context appContext, @NonNull WorkerParameters params) {
    super(appContext, params);
  }

  @Override
  public ListenableWorker.Result doWork() {
    // Do your work here.
    Data input = getInputData();

    // Return a ListenableWorker.Result
    Data outputData = new Data.Builder()
        .putString(“Key”, “value”)
        .build();
    return Result.success(outputData);
  }

  @Override
  public void onStopped() {
    // Cleanup because you are being stopped.
  }
}

ListenableWorker:

import android.content.Context;
import androidx.work.ListenableWorker;
import androidx.work.ListenableWorker.Result;
import androidx.work.WorkerParameters;
import com.google.common.util.concurrent.ListenableFuture;

class MyWorker extends ListenableWorker {

  public MyWorker(@NonNull Context appContext, @NonNull WorkerParameters params) {
    super(appContext, params);
  }

  @Override
  public ListenableFuture<ListenableWorker.Result> startWork() {
    // Do your work here.
    Data input = getInputData();

    // Return a ListenableFuture<>
  }

  @Override
  public void onStopped() {
    // Cleanup because you are being stopped.
  }
}
like image 418
appukrb Avatar asked Oct 17 '22 06:10

appukrb


1 Answers

Workers run synchronously on a background thread. ListenableWorkers are expected to run asynchronously - they are invoked on the main thread and you are supposed to offer all the threading (such as moving them to a background thread). Workers are simpler and are expected to be the basic building block of your app. You can read more about them here:

https://developer.android.com/reference/androidx/work/Worker https://developer.android.com/reference/androidx/work/ListenableWorker

If you're interested, you can also check out CoroutineWorker and RxWorker.

like image 150
SumirKodes Avatar answered Oct 27 '22 09:10

SumirKodes