How do i get the Output Data from a Worker? (MVVM + WorkManager + Room)

Viewed 1086

I am using MVVM and enqueuing a worker from my Repository. The workers job is just to insert some data into the database but i would like to get access to some Output data when the background task is finished so i can verify if the data went inside the Database without issue or not. I tried using WorkInfo.State or get the data with getOutputData but it doesn't seem to work for some reason. Any ideas on how i can achieve this?

Here is the code for reference:

AddWorkoutWorker.java

public class AddWorkoutWorker extends Worker {

    public static final String WORK_WORKOUT_NAME = "workout";
    public static final String WORK_WORKOUT_TYPE = "type";
    public static final String WORK_FAILURE_TAG = "failed";
    public static final String WORK_SUCCESS_TAG = "success";
    private static final String WORKER_TAG = "Worker Tag";
    private WorkoutDAO workoutDAO;
    private AppDatabase database;
    Boolean workSuccess;

    //Worker constructor
    public AddWorkoutWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        database = AppDatabase.getInstance(context);
        workoutDAO = database.workoutDAO();
    }

    @NonNull
    @Override
    public Result doWork() {

        //Gets input data
        Data inputData = getInputData();
        String workoutName = inputData.getString(WORK_WORKOUT_NAME);
        String workoutType = inputData.getString(WORK_WORKOUT_TYPE);


        if (workoutName != null && workoutType != null){
            //Inserts item in database through DAO
            Log.d(WORKER_TAG,"Worker data passed: "+workoutName + workoutType);
            Workout workout = new Workout(workoutName, workoutType);
            workoutDAO.insertSingleWorkout(workout);
        }else{
            //Returns false if the worker doesn't add the item to the database
            workSuccess = false;
            Data output = new Data.Builder()
                    .putBoolean(WORK_FAILURE_TAG,workSuccess)
                    .build();
            return Result.failure(output);
        }

        //Returns true if the worker adds the item to the database
        workSuccess = true;
        Data output = new Data.Builder()
                .putBoolean(WORK_SUCCESS_TAG, workSuccess)
                .build();

        return Result.success(output);
    }
}

AddWorkoutRepository.java

public class AddWorkoutRepository{

    private static final String REPOSITORY_TAG = "REPOSITORY TAG";
    public static final String WORKER_QUEUE_TAG = "Importing Single Workout";
    public WorkoutDAO workoutDAO;
    private final WorkManager workManager;
    private AppDatabase database;
    //private LiveData<List<Workout>> workouts;



    public AddWorkoutRepository(Application application){

        database = AppDatabase.getInstance(application);
        workoutDAO = database.workoutDAO();
        workManager = WorkManager.getInstance(application.getApplicationContext());
        //workouts = workoutDAO.getAllWorkoutsLiveData();

    }

    /*public LiveData<List<Workout>> getAllWorkouts(){
        return workouts;
    }*/

    public void insertWorkout(Workout workout){

        String workoutName = workout.getWorkoutName();
        String workoutType = workout.getWorkoutType();

        Log.d(REPOSITORY_TAG, "Insert Values passed: "+workoutName + workoutType);

        Data data = new Data.Builder()
                .putString(WORK_WORKOUT_NAME, workoutName)
                .putString(WORK_WORKOUT_TYPE, workoutType)
                .build();

        OneTimeWorkRequest importDataRequest = new OneTimeWorkRequest.Builder(AddWorkoutWorker.class)
                .setInputData(data)
                .addTag(WORKER_QUEUE_TAG)
                .build();

        workManager.enqueue(importDataRequest);

        Log.d(REPOSITORY_TAG, "After work manager task OK");

    }

}
1 Answers

Ok so i figured it out. I used the LiveData obj that is available from WorkInfo to get the output data and the state of the task.

  1. First thing i did was declare the LiveData obj inside my ViewModel private LiveData<List<WorkInfo>> workerOutPut;
  2. Then in the view model constructor initialize my LiveData like this workerOutPut = workManager.getWorkInfosByTagLiveData(ADD_WORKOUT_WORKER_QUEUE_TAG);
  3. Made a getter for the LiveData (in the ViewModel ofcourse)
  4. Then i just simply made an Observer inside my activity that checked the status of the Worker based on a boolean i set inside the Worker output Data.

And that was it. I am new to all this so if anyone has anything to add please feel free to do so. I will post the complete code for other new "players" to help them a bit.

Worker.java

public class AddWorkoutWorker extends Worker {

    public static final String WORK_WORKOUT_NAME = "workout";
    public static final String WORK_WORKOUT_TYPE = "type";
    public static final String WORK_FAILURE_TAG = "failed";
    public static final String WORK_SUCCESS_TAG = "success";
    private static final String ADD_WORKOUT_WORKER_TAG = "Worker Tag";
    private WorkoutDAO workoutDAO;
    private AppDatabase database;
    Boolean workSuccess;

    //Worker constructor
    public AddWorkoutWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        database = AppDatabase.getInstance(context);
        workoutDAO = database.workoutDAO();
    }

    @NonNull
    @Override
    public Result doWork() {

        //Gets input data
        Data inputData = getInputData();
        String workoutName = inputData.getString(WORK_WORKOUT_NAME);
        String workoutType = inputData.getString(WORK_WORKOUT_TYPE);


        if (workoutName != null && workoutType != null){
            //Inserts item in database through DAO
            Log.d(ADD_WORKOUT_WORKER_TAG,"Worker data passed: "+workoutName + workoutType);
            Workout workout = new Workout(workoutName, workoutType);
            workoutDAO.insertSingleWorkout(workout);
        }else{
            //Returns false if the worker doesn't add the item to the database
            workSuccess = false;
            Data output = new Data.Builder()
                    .putBoolean(WORK_FAILURE_TAG,workSuccess)
                    .build();
            return Result.failure(output);
        }

        //Returns true if the worker adds the item to the database
        workSuccess = true;
        Data output = new Data.Builder()
                .putBoolean(WORK_SUCCESS_TAG, workSuccess)
                .build();

        return Result.success(output);
    }
}

ViewModel.java

public class AddWorkoutViewModel extends AndroidViewModel {

    private static final String WORKOUT_VIEW_MODEL = "Workout View Model";
    private AddWorkoutRepository repository;
    private AddWorkoutWorker worker;
    private WorkManager workManager;
    private Boolean check;
    private LiveData<List<WorkInfo>> workerOutPut;
    //private LiveData<List<Workout>> AllWorkouts;

    public AddWorkoutViewModel(@NonNull Application application) {
        super(application);
        repository = new AddWorkoutRepository(application);
        workManager = WorkManager.getInstance(application);
        workerOutPut = workManager.getWorkInfosByTagLiveData(ADD_WORKOUT_WORKER_QUEUE_TAG);
        //AllWorkouts = repository.getAllWorkouts();
    }


    /*public LiveData<List<Workout>> getWorkoutList(){
        return AllWorkouts;
    }*/

    public LiveData<List<WorkInfo>> checkWorkerStatus(){
        return workerOutPut;
    }

    public void insertData(Workout workout){
        Log.d(WORKOUT_VIEW_MODEL,"View Model Insert Data");
        repository.insertWorkout(workout);
    }
}

The observer inside the activity

//Observes LiveData from WorkManager AddWorkoutWorker to validate if worker functioned correctly
        mAddWorkoutViewModel.checkWorkerStatus().observe(this, new Observer<List<WorkInfo>>() {
            @Override
            public void onChanged(List<WorkInfo> workInfos) {

                if(workInfos.isEmpty() || workInfos == null){
                    Log.d(ADD_WORKOUT_WORKER_EMPTY,"Worker is empty");
                }else{

                    if(workInfos.get(0).getOutputData().getBoolean(WORK_SUCCESS_TAG, false)){

                        //If works do stuff here

                    }else{
                        Toast.makeText(AddWorkoutActivity.this,"Something went wrong. Try again.",Toast.LENGTH_LONG);
                    }

                }

            }
        });

For those that might wonder. I use workInfos.get(0) because we only have ONE single worker that we are checking. I would assume if we had multiple workers at the same time we could have made a case for each one.

Related