'Android JetPack - run code on WorkRequest completion

Let's say I need to fetch data from a db asynchronously and then pass it to a recyclerview's adapter. Using AsyncTask, I can do the following:

void getItemsFromDb() {
        new AsyncTask<Void,Void,Void>(){
            @Override
            protected Void doInBackground(Void... voids) {
                this.items = getFromDb(); // items is the adapter's data set
                return null;
            }
            @Override
            protected void onPostExecute(Void unused) {
                super.onPostExecute(unused);
                this.adapter.notifyDataSetChanged();
            }
        }.execute();

If I were to be doing this using WorkRequest, the fetching would look like this:

class MyWork extends Worker {
   @NonNull
   @Override
   public Result doWork() {
       getItemsFromDb() // <---- how do I pass this to my adapter?
       return Result.success();
   }
}


WorkRequest myWorkRequest = OneTimeWorkRequest.from(MyWork.class);

How would I get the items from a db and pass them to the adapter? And how do I call notifyDataSetChanged in the UI thread after the background work has completed?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source