Based on this post by Florina Muntenescu I have 2 questions:
Question 1: In the following situation considering a Respository
response SomeApiResult:
sealed class SomeApiResult<out T : Any> {
object Success : SomeApiResult<Unit>()
object NoAccount : SomeApiResult<Unit>()
sealed class Error(val exception: Exception) : SomeApiResult<Nothing>() {
class Generic(exception: Exception) : Error(exception)
class Error1(exception: Exception) : Error(exception)
class Error2(exception: Exception) : Error(exception)
class Error3(exception: Exception) : Error(exception)
}
}
Latter when using when
in my ViewModel
I wont be able to do something like:
when (result: SomeApiResult) {
...
is SomeApiResult.Error.Error1,
is SomeApiResult.Error.Error2 -> {
// it will fail with "Unresolved reference: exception"
result.exception
}
is SomeApiResult.Error.Error3 -> {
...
}
}
How can I solve this?
This is valid though:
when (result: Result<Int>) {
...
is SomeApiResult.Error -> result.exception.message
}
Question 2: When creating the error response I have to create a GenericError because if I try to instantiate the sealed class
I get an error. This is how I make it work:
is Result.Error ->
when (result.exception) {
is Error1 -> SomeApiResult.Error.Error1(result.exception)
is Error2 -> SomeApiResult.Error.Error2(result.exception)
...
else -> SomeApiResult.Error.Generic(result.exception)
}
In my ViewModel
I wont be querying for Error.Generic
.
Instead, I'll use is SomeApiResult.Error
as shown above (like else ->
"other errors"). Is this the right way?