如何在Retrofit2中使用协程?

时间:2019-11-23 12:25:46

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

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

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)
    }
}

2 个答案:

答案 0 :(得分:0)

response.isSuccessful检查后您在做什么?

尝试在适配器中设置响应,然后notifyDataSetChanged

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

答案 1 :(得分:0)

您的改造和协程实施效果很好, 成功检查响应后,您只是没有更新适配器列表

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

您也无法在协同程序中显示Toast,而是将其包装在runOnUiThread{}