I want to unwrap a Result object that is defined in a Kotlin shared module for a Kotlin Multiplatform Project in iOS and Android.
Kotlin definition of Result object:
sealed class Result<out T> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val errorMessage: String) : Result<Nothing>()
object Loading : Result<Nothing>()
}
The Result is returned from an API response in Kotlin as Result.
class SearchAPI {
private val baseUrl = "https://api.example.com"
@OptIn(InternalAPI::class)
suspend fun getSearchResponse(): Result<SearchResponse>{
val client = HttpClient() {
install(HttpTimeout) {
requestTimeoutMillis = 60_000 // 30 seconds
}
}
try {
val response = client.post(baseUrl) {
...
return Result.Success(searchResponse)
}
In Kotlin I can unwrap a API response from Ktor like this
fun searchCounts() {
viewModelScope.launch(Dispatchers.IO) {
val result = searchAPI.getSearchResponse()
// Handle the result, e.g., update UI or show error message
when (result) {
is Result.Success -> {
val searchResponse = result.data
_counts.value = searchResponse
// Handle successful response
}
is Result.Error -> {
// val errorMessage = result.message
// Handle error
}
Result.Loading -> TODO()
else -> {}
}
}
}
However, when unwrapping it in SwiftUI using switch clause, I get the error
"Reference to member 'success' cannot be resolved without contextual type.".
And same for Error and Loading. Can someone show me how to use the Result object in SwiftUI?
This is the code with the error SwiftUI:
func searchCounts() async {
do {
let result = try await searchAPI.getSearchResponse()
// Handle successful response
print(result.self)
switch result {
case .success(let searchResponse): // Error Message
self.counts = searchResponse
// Handle successful response
case .failure(let error): // Error Message
// Handle error
print("Error: \(error.localizedDescription)")
case .loading(): // Error Message
print("Error:")
}
} catch {
// Handle error
print("Error: \(error)")
}
}
My multiplatform approach in general works, so I can print the body of the Kotlin API Request as JSON from SwiftUI, I just can't handle Success and Error states.