【问题标题】:How to use Coroutines with Retrofit2?如何在 Retrofit2 中使用协程?
【发布时间】:2020-03-19 07:32:02
【问题描述】:

我正在使用 Retrofit2 和 Kotlin 协程从 api 获取数据以显示在 RecycerView 中。我刚刚开始学习改造和协程,目前数据没有显示,我不知道如何解决它!我认为问题可能出在协程代码上。请问有人可以帮我吗?

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var recyclerView: RecyclerView = findViewById(R.id.rockets_list)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = RecyclerAdapter(List<RocketData>())


        CoroutineScope(IO).launch {
            val response = ApiInterface.getApi().getRockets()
            Log.i("code",response.toString())
            withContext(Dispatchers.Main) {
                try {
                    if (response.isSuccessful) {
                        recyclerView.adapter
                    } else {
                        Toast.makeText(this@MainActivity, "Error ${response.code()}", Toast.LENGTH_SHORT).show()

                    }
                } catch (e: HttpException) {
                    Toast.makeText(this@MainActivity, "Exception ${e.message}", Toast.LENGTH_SHORT).show()

                }
            }

        }
    }
}
interface ApiInterface {
    @GET("rockets")
    suspend fun getRockets(): Response<List<RocketData>>

    companion object {

        fun getApi(): ApiInterface = Retrofit.Builder()
            .baseUrl("https://api.spacexdata.com/v3/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiInterface::class.java)
    }
}

【问题讨论】:

  • 如我所见,您在检查if (response.isSuccessful)后没有更新适配器项目@

标签: api kotlin android-recyclerview retrofit kotlin-coroutines


【解决方案1】:

response.isSuccessfulcheck 之后你在做什么??

尝试在 Adapter 中设置响应,然后 notifyDataSetChanged

recyclerView.adapter.items = response
recyclerView.adapter.notifyDataSetChanged()

【讨论】:

    【解决方案2】:

    您的改造和协程实现工作正常, 您只是在响应检查成功后没有更新您的适配器列表

    if (response.isSuccessful) {
        recyclerView.adapter.list = response.body
        recyclerView.adapter.notifyDataSetChanged()
    }
    

    你也不能在协程中显示Toast,将它包裹在runOnUiThread{}

    【讨论】:

      猜你喜欢
      • 2020-09-25
      • 2017-03-29
      • 2018-04-16
      • 2020-10-29
      • 2021-11-11
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多