how to pass object as input to WorkManager without Serialization?
Asked Answered
T

1

11

I need to pass complex object to WorkManager. Or I need to serialize object which contains Livedata and Date.

It throws java.lang.IllegalArgumentException: Key cabinId2 has invalid type class com.example.sonyadmin.data.Task

     val data = workDataOf("cabinId2" to task)
     val uploadWorkRequest = OneTimeWorkRequestBuilder<WManager>()
         .setInputData(data)
         .build()
Threewheeler answered 27/4, 2019 at 2:48 Comment(0)
S
12

WorkManager's Data class only accepts some specific types as values as explained in the reference documentation:

A persistable set of key/value pairs which are used as inputs and outputs for ListenableWorkers. Keys are Strings, and values can be Strings, primitive types, or their array variants.

On top of that there's a size limit of about 10KB, specified by the constant MAX_DATA_BYTES.
If the data is not too big, you may want to serialize it to a String and use that as inputData in your WorkRequest. The alternative is to just put a reference of your objects in the inputData. WorkManager's codelab has a sample of this where an URI of an image is passed into a WorkRequest and the image is on the filesystem.

Stubbs answered 28/4, 2019 at 8:28 Comment(2)
Thanks. However, how would one send a list of Uris? Isn't reference a confusing word to use here. Don't send references, because those references might not be available when the OS launches the work again later. Uri is the only type of reference that will be available, so its clearer to say Uri.Silberman
Annoyingly, this limitation of Data is not enforced in code: i.e. workDataOf takes in Pair<String, Any?>, which is probably what made people ask OP's question in the first place: there is a method to put data in, but no method to take it out once the work starts.Silberman

© 2022 - 2024 — McMap. All rights reserved.