WorkManager Data.Builder does not support Parcelable

前端 未结 6 1152
心在旅途
心在旅途 2021-02-20 06:18

When you have a big POJO with loads of variables (Booleans, Int, Strings) and you want to use the new Work Manager to start a job. You then create a Data file which gets added t

6条回答
  •  臣服心动
    2021-02-20 06:51

    First you need to know that the value holder for data is private val mValues which you can not exactly work with to add parcelable to the data but there is a workaround to make the process at least less tedious

    val Data.parcelables by lazy {
       mutableMapOf()
    }
    
    fun Data.putParcelable(key:String, parcelable:Parcelable) : Data{
      parcelables[key] = parcelable
      // to allow for chaining 
      return this
    }
    // in order to get value in the Work class created  Wrok.doWork method
    fun Data.getParcelable(key:String): Parcelable? = parcelables[key]
    
     // build  process
    
     /// you can not add putParcelable to Builder class either since mValues in the builder is also private and Builder.build() return Data(mValues)
     val data = Data.Builder()
                .putBoolean("one",false)
    
                .build()
                .putParcelable("name",parcelable)
    
    val request = OneTimeWorkRequest.Builder().setInputData(data).build()
    

提交回复
热议问题