androidx.work.Data に詰め込んでいいのは 10KB まで

結論

Q.10KB を超えるとどうなる
A.IllegalStateException を吐く

詳しく

Jetpack WorkManager を使った処理の中でやり取りしたいデータを詰めるとき、こんな風にする。

// https://developer.android.com/reference/kotlin/androidx/work/package-summary#workdataof
import androidx.work.workDataOf

val inputData = workDataOf(
    sometingKey to "somethingData",
    // anything more data
)

このとき、いくらでもデータを突っ込めるわけではなく、10240 Bytes を超える量を入れてしまうと IllegalStateException が吐かれてしまう。その処理を司っているコードがここ。

https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:work/workmanager/src/main/java/androidx/work/Data.java;l=386-422?q=androidx.work.Data

// androidx.work.Data 416〜420行目
if (outputStream.size() > MAX_DATA_BYTES) {
    throw new IllegalStateException(
            "Data cannot occupy more than " + MAX_DATA_BYTES
                    + " bytes when serialized");
}

MAX_DATA_BYTES はシリアル化されるデータの最大容量を定めている定数で、2020/04/06 時点では 10240 (10KB) という値が設定されている。

The maximum number of bytes for Data when it is serialized (converted to a byte array). Please see the class-level Javadoc for more information.

Constant Value: 10240 (0x00002800)

androidx.work.Dataドキュメントのトップにも、軽量なコンテナなので入れ過ぎないようにねとある。 アプリの中で生成したデータならともかく、アプリ外から拾ってくるデータを扱うようなケースでは意外とこの上限にヒットすることがあるので気をつけたい。

This is a lightweight container, and should not be considered your data store. As such, there is an enforced MAX_DATA_BYTES limit on the serialized (byte array) size of the payloads. This class will throw IllegalStateExceptions if you try to serialize or deserialize past this limit.

developer.android.com

また、ガイドドキュメントでは、もし 10KB の制限を超えるデータを扱いたいときには Jetpack Room などを用いてデータを別の場所に置くことを勧めている。

Note: Data objects are intended to be small and values can be Strings, primitive types, or their array variants. If you need to pass more data in and out of your Worker, you should put your data elsewhere, such as a Room database. There is a maximum size limit of 10KB for Data objects.

developer.android.com