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

Time:08-27

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
                 .build();

OneTimeWorkRequest workRequest = new OneTimeWorkRequest
                                  .Builder(MyWorker.class)
                                  .build();

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

CodePudding user response:

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.

  • Related