Hello! I’m currently having an issue where wrappin...
# coroutines
r
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
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
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
Should be fixed in JVM IR FYI.
m
I hope so. I keep creating inline classes and remove the
inline
days after because I keep getting exceptions 😄