How do I exclude a property in a data class from b...
# android
h
How do I exclude a property in a data class from being Parcelized?
Copy code
@Parcelize
data class State(
  val userId: String = 1234,
  val userResource: Resource<User> = Resource.Uninitialized
): Parcelable
I want to exclude the
userResource
property from being Parcelized, as the
Resource
class is not Parcelable. Here is the warning I get from the IDE:
Type is not directly supported by @Parcelize. Annotate the field with @RawValue if you want to be serialized using 'writeValue()'
@Transient
does not work, and neither does
@IgnoreOnParcel
(I get the warning that it is not applicable on properties in primary constructor). Any way to solve this?
n
Have you tried remove this property from the primary constructor?
h
That works, but it requires me to create a secondary constructor. All the parcelable properties go in the primary constructor, and the un-parcelable ones go in the secondary constructor. However this involves a dealbreaker: we can not have `val`s in secondary constructors. So the only solution is to do something like this:
Copy code
@Parcelize
data class State(
  val userId: Int = 1234
): Parcelable {
  private lateinit var resource: Resource<User>
  constructor(missionId: Int, userRes: Resource<User>) {
    this.resource = userRes
  }
}
This, of course is not great because I lose immutability (resource is now a var). Also, the auto-generated copy function does not accept secondary constructor params.
n
yeah… you’re right… 😞 maybe you can wrap your class and just serialize the internal props that you want… 🤷‍♂️
r
a simple way would just the factor pattern
factory pattery
or the secondary constructor ,would just call the primary constructor. or don't use the @Parcerlize annotation , and just override everything manually
206 Views