androidkotlinandroid-recyclerviewkotlin-coroutinesandroid-mvp

Updating Recyclerview adapter from suspend function


I'm trying to load and display books from the books api but the information doesn't display. I was able to get it to display if I used the debugger and step through but not from starting off.

    val client = OkHttpClient()
    val request = Request.Builder()
        .url(url)
        .build()

    client.run {
        newCall(request).enqueue(object : Callback {
            override fun onFailure(call: okhttp3.Call, e: IOException) {
                e.printStackTrace()
            }

            override fun onResponse(call: okhttp3.Call, response: Response) {
                if (!response.isSuccessful) {
                    System.err.println("Response unsuccessful")
                    return
                }
                val response = response.body?.string()
                val books = response?.let { parse(it) }
                if (books != null) {
                    list.addAll(books.bookItems)
                }
            }
        })
        delay(500)
    }
    return list
}

Edit: Just needed to increase the delay time and remove renderBooks() call


Solution

  • You call presenter.getBooks before the fragment's view is initialized. Try place it inside onViewCreated.