Skip to content

throwing a Serializable RuntimeException in OnNext requires OnNext value to be Serializable as well #4562

@saharh

Description

@saharh

when throwing a runtime exception during OnNext, the exception is wrapped within OnErrorThrowable$OnNextValue, which features access to the value emitted in OnNext. this feature comes at a cost - If one would wish to serialize/deserialize the exception or any object containing that exception, one would also be required to have the type of item emitted by OnNext also implement Serializable (which could lead to whole hierarchy of objects be serializable). While the original runtime exception thrown is serializable, the OnErrorThrowable$OnNextValue which includes reference to the onnext emitted item, isn't.
This leads to java.io.NotSerializableException thrown when trying to serialize the exception:

Caused by: java.io.NotSerializableException: com.example.SomeUnserializableObject
        at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1344)
        at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1651)
        at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1497)
        at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1461)
        at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:959)
        at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:360)
        at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1054)
        at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1384)
        at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1651)
        at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1497)
        at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1461)
        at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:959)
        at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:360)
        at java.lang.Throwable.writeObject(Throwable.java:436)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.io.ObjectO

I dont see any way around it other than avoiding throwing of RuntimeException during onNext, and instead move to flatmap and return Observable.error(exception).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions