我正在尝试通过网络服务+改造和异步回调来构建应用。
我有一个密封的科特林
sealed class StateDevol {
object Loading: StateDevol()
object Success: StateDevol()
class showError(val error: String) : StateDevol()
}
这是我的带有改进版本的存储库,改进版本可以正常工作,并且我收到200条代码。
主要问题是:我从实时数据中收到“正在加载”更改,但没有收到其余更改。
class WebServiceDevolucionESA : WebserviceInterface
{
var mutableLiveData = MutableLiveData<StateDevol>()
override fun invoke(reference: String) : MutableLiveData<StateDevol> {
mutableLiveData.value = StateDevol.Loading
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
val retrofit = Retrofit.Builder()
.baseUrl("BASE_URL")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
val service = retrofit.create(Api_Devolucion_R::class.java)
/*PREPARACION DE CUERPO*/
var jsonInputString = "...A JSON..."
val requestBody = RequestBody.create(MediaType.parse("text/plain"), jsonInputString)
val call = service.doReturn(requestBody)
call.enqueue(object : Callback<ReturnPojo> {
override fun onResponse(call: Call<ReturnPojo>, response: Response<ReturnPojo>) =
if (response.code() == 200) {
val responseString = response.body()
mutableLiveData.value = StateDevol.Success
System.out.println("Set after return")
}
else
{
mutableLiveData.value = (StateDevol.showError("Partial Error"))
}
override fun onFailure(call: Call<ReturnPojo>, t: Throwable) {
System.out.println("Fatal Error")
mutableLiveData.value = StateDevol.showError("Fatal Error")
}
})
System.out.println("Exit")
return mutableLiveData
}
}
在存储库类中返回此信息
class RepoDev(private val webserviceDevol: WebserviceInterface)
{
fun invoke(reference: String) : LiveData<StateDevol>
{
return web.invoke(reference)
}
}
一个视图模型
class ModelViewDev ( private val repo : RepoDev) : ViewModel()
{
var state = MutableLiveData<StateDevol>()
fun dispatch(reference: String)
{
state.value = repo.invoke(reference).value
}
fun getStatus(): LiveData<StateDevol> {
return state
}
}
class ModelViewDev Factory(private val repo: RepoDev) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return ModelViewDev (repo) as T
}
}
最后是视图
viewModel = ViewModelProviders.of(this, ModelViewDevolucionFactory(RepositorioDevolucion(WebServiceDevolucionESA())))
.get(ModelViewDevolucion::class.java)
//viewModel.getStatus().observe(this, stateObserverChanged)
viewModel.state.observe(::getLifecycle, ::updateUI)
private fun updateUI(estado: StateDevol?) {
when (estado) {
StateDevol.Loading -> unableButton()
StateDevol.Success -> returnOK()
is StateDevol.showError -> changeError(estado.error)
}
}
正如我所说,我正在接收第一个“正在加载”信号,但没有接收到排队函数(成功或错误)中的回调值