How do I send a non-basic type object to worker?


Please help
How do I send a non-basic type object to a worker?
For example, a ViewModel object.

My code is as follows

MyViewModel myViewModel = new ViewModelProvider(HomeActivity.this).get(MyViewModel.class);
Data data = new Data.Builder()
                 .putString("Parameter1", "Test")
                 .put("Parameter2", myViewModel) // It's invalid in this row

OneTimeWorkRequest workRequest = new OneTimeWorkRequest

WorkManager workManager = WorkManager.getInstance(this);
workManager.enqueueUniqueWork("MyUniqueWorker", ExistingWorkPolicy.KEEP, workRequest);


You can’t put a ViewModel or anything like that in there. Remember, a job will be run later and may not be run inside the same process you have now. So it’s going to be serialized to disk, so the scheduler can recreate it later on. That means any data needs to be serializable. So even if you could put a ViewModel in there, it wouldn’t act like you hope- it wouldn’t be the same ViewModel when reserialized so it wouldn’t trigger any observers.

Instead, write a function that takes the ViewModel and turns it into a Data structure by serializing only the important pieces of data inside of the ViewModel- the data the job will actually use.

Answered By – Gabe Sechan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published