https://kotlinlang.org logo
#coroutines
Title
# coroutines
r

Ricardo C.

10/16/2020, 2:59 PM
Hello! I’m currently having an issue where wrapping a callback + switching the context will throw even when wrapping everything inside a Result. The weird part is that I’m not throwing anything, just creating a Result.failure with the exception. Removing withContext will fix the crash, but then I’m not sure how to run on another thread (Code inside the thread)
Copy code
suspend fun <R, E> invokeMethod(
    name: String,
    onSuccessClass: Class<R>,
    onErrorClass: Class<E>,
    vararg args: Any
): Result<R> = withContext(dispatcher) {
    suspendCoroutine { continuation ->
        val onSuccess = { result: String ->
            val data = parseJson(onSuccessClass, result)
            continuation.resume(Result.success(data))
        }

        val onError = { error: String ->
            val data = parseJson(onErrorClass, error)
            continuation.resume(Result.failure(DataException(data.toString())))
        }

        runtime.invokeMethod(name, onSuccess, onError, *args)
    }
}
this will crash with the exception that I created (DataException) just like if I threw it instead of passing it as a value
If I call invokeMethod but it lands on onSuccess callback instead, it’ll work properly
okay so this happens because of kotlin’s Result class. I replaced it with my own implementation. Somehow coroutines unwrap my own created Result?
not an expected behavior
m

Marc Knaup

10/16/2020, 3:37 PM
Result
is an
inline class
which are still experimental. There are edge cases where they aren’t handled properly by the compiler. I guess your
Result
is unintentionally unwrapped which leads to the exception.
Also,
Result
isn’t supposed to be used as a general purpose return type.
r

Ricardo C.

10/16/2020, 3:42 PM
well that’s fair. I was really not expecting to hit an issue, but here we are. Going to move forward with my own Result class. Thanks!
l

louiscad

10/16/2020, 4:00 PM
Should be fixed in JVM IR FYI.
m

Marc Knaup

10/16/2020, 4:00 PM
I hope so. I keep creating inline classes and remove the
inline
days after because I keep getting exceptions 😄
3 Views