6

I was wondering if it would be possible to pass a lambda to Intent in kotlin, since lambdas are Serializable, but with this code I am getting error when creating a PendingIntent.

val bundle = bundleOf(ACTION to { pause() })
val playButtonIntent = Intent(this, MusicService::class.java).apply {
        putExtras(bundle)
}
val pendingPlayIntent = PendingIntent.getService(this, 1, playButtonIntent, 0)

error:

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object
Jayson Minard
  • 84,842
  • 38
  • 184
  • 227
tomas
  • 376
  • 1
  • 5
  • 17
  • They are @Pawel, that isn't the issue on its own. – Jayson Minard Nov 19 '18 at 05:43
  • I've created a wrapper TrackedReference that is parcelable and serializable without requiring marshaling for the underlying type: https://stackoverflow.com/a/64944753/3405387 – Lukas Nov 21 '20 at 16:28

1 Answers1

5

A Lambda itself is serializable. But in your case, it closes on a variable bundle of some type that likely is not serializable. So it is making a Lambda class that includes a member to hold that closed variable. You cannot make a serializable object that contains things inside it that break serialization.

So you need to find a way not to hold that bundle class, or need to make it serializable.

See this other question in SO for more details: https://stackoverflow.com/a/48870902/3679676

Jayson Minard
  • 84,842
  • 38
  • 184
  • 227