【发布时间】:2021-12-15 03:56:12
【问题描述】:
我正在尝试让我的回收站视图等到我的改造功能完成。改造功能存储在视图模型中,而回收器视图在我的活动中。我可以让它延迟工作,但这似乎不是一个好方法。
GlobalScope.launch {
suspend {
val txt = findViewById<TextView>(R.id.textbox)
viewModel.getStaff()
delay(10000)
withContext(Dispatchers.Main) {
Log.d("coroutineScope", "#runs on ${Thread.currentThread().name}")
createRV(viewModel.pictureList, viewModel.actorList, viewModel.characterList, viewModel.houseList)
}
}.invoke()
这是我的改造功能
suspend fun getStaff(){
val retrofit = Retrofit.Builder()
.baseUrl("http://hp-api.herokuapp.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val service = retrofit.create(HarryPotterApi::class.java)
val call = service.staff()
try {
call.enqueue(object : Callback<Staff> {
override fun onResponse(call: Call<Staff>, response: Response<Staff>) {
if (response.code() == 200) {
val characterData = response.body()!!
pictureList.add(characterData[0].name)
actorList.add(characterData[0].name)
characterList.add(characterData[0].name)
houseList.add(characterData[0].name)
}
}
override fun onFailure(call: Call<Staff>, t: Throwable) {
}
})}catch (e: IOException) {
e.printStackTrace()
}
}
【问题讨论】:
-
Retrofit 从
2.6.0开始支持协程。只需将您的staff()函数挂起,然后您就可以同步使用它,从而使您的代码更加简单。 -
你的意思是getStaff()。如果是这样,但它是灰色的,并且说它是多余的。
-
不,我的意思是
HarryPotterApi.staff()。我没有您的完整代码,但您可以将其设置为:suspend fun staff(): Staff,然后像这样使用它:val characterData = service.staff()。然后你就可以删除getStaff()里面60%的代码,同时解决等待结果的问题。 -
好的,我在答案中添加了我的意思。请注意,这可能不是一个完整的示例。