几天来,我一直有这个问题,我无法解决,因为它总是给我一个错误时,从api加载数据,帮助我的问题:
致命异常:DefaultDispatcher-worker-1java.lang.IllegalStateException:期望的BEGIN_ARRAY,但在第1行第2列路径$
@HiltViewModel
class RMViewModel @Inject constructor(private val useCase: RMGetCharacterUseCase) : ViewModel() {
private val _state = MutableStateFlow<RMListState>(RMListState.Empty)
val state: StateFlow<RMListState> = _state
init {
getAllCharacters()
}
private fun getAllCharacters()=viewModelScope.launch(Dispatchers.IO){
_state.value = RMListState.Loading
val data = useCase.invoke()
if (data.data.isNullOrEmpty()) _state.value = RMListState.Fail(data.message ?: "An unexpected error occured")
else _state.value = RMListState.Success(data.data ?: emptyList())
}
}
用例
class RMGetCharacterUseCase @Inject constructor(private val repo: RMRepository) {
suspend operator fun invoke(): Validator {
try {
val bundle = repo.getCharacters().map { it.toDomain() }
return if (bundle.isNullOrEmpty()) Validator("FALLO")
else Validator("retorno", bundle)
}catch (e: HttpException) {
return Validator(e.localizedMessage ?: "An unexpected error occured")
} catch (e: IOException) {
return Validator("Couldn't reach server. Check your internet connection.")
}
}
}
库
class RMRepositoryImpl @Inject constructor(private val api: RMApiService):RMRepository{
override suspend fun getCharacters(): List<Result> = api.getCharacters()
}
/p> 数据域interface RMApiService {
@GET(Constants.END_POINT)
suspend fun getCharacters():List<Result>
}
data class Result(
val created: String?,
val episode: List<String?>?,
val gender: String?,
val id: Int?,
val image: String?,
val name: String?,
val species: String?,
val status: String?,
val type: String?,
val url: String?
)
data class RM(
val created: String?,
val episode: List<String?>?,
val gender: String?,
val id: Int?,
val image: String?,
val name: String?,
val species: String?,
val status: String?,
val type: String?,
val url: String?
)
fun Result.toDomain()= RM(
created=created,
episode=episode,
gender=gender,
id=id,
image=image,
name=name,
species=species,
status=status,
type=type,
url=url
)
尝试返回Result
对象而不是List<Result>
:
interface RMApiService {
@GET(Constants.END_POINT)
suspend fun getCharacters(): Result
}