Search code examples
androidkotlinkotlin-coroutineskodein

Kotlin, Coroutines, Kodein and list for RecyclerView


I just started learning of Kotlin Android and I decided to use in my first Kotlin app Coroutines and Kodein library. My problem is returning list of the objects created in the Room Database. I know how to set simple list for Recyclerview, but I have problem with setting list of the objects in Recyclerview by Coroutines.

Function from activity where is using Recyclerview:

 private fun getCities() = launch(Dispatchers.Main) {
    var locationList = addLocationViewModel.location.await()
    locationList.observe(this@AddLocationActivity, Observer {

        viewAdapter = LocationAdapter(locationList, this)
    })
}

As you can see the first parameter in the LocationAdapter is locationList and this one is underlined by red color. The Error means:

Type mismatch.
 Required: kotlin.collections.ArrayList<Location>
 Found: LiveData<List<Location>>

How to resolve this?

Adapter:

class LocationAdapter(
private val cities: ArrayList<Location>,
private val context: Context
) : RecyclerView.Adapter<LocationAdapter.LocationViewHolder>() {

private var removedPosition: Int = 0
private var removedItem: String = ""


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocationViewHolder {
    val layoutInflater = LayoutInflater.from(context)
    val contactRow = layoutInflater.inflate(R.layout.location_recyclerview_item, parent, false)
    return LocationViewHolder(contactRow)
}

override fun getItemCount(): Int {
    return cities.size
}

override fun onBindViewHolder(holder: LocationViewHolder, position: Int) {
    val location = holder.view.location_text_view_item

    location.text = cities.get(position).toString()
}

class LocationViewHolder(val view: View) : RecyclerView.ViewHolder(view)

fun removeItem(viewHolder: RecyclerView.ViewHolder) {
    removedItem = viewHolder.adapterPosition.toString()
    removedItem = cities[viewHolder.adapterPosition].toString()

    cities.removeAt(viewHolder.adapterPosition)
    notifyItemRemoved(viewHolder.adapterPosition)


}


}

ViewModel:

class AddLocationViewModel(
private val locationRepository: LocationRepository
) : ViewModel() {

val location by lazyDeferred {
    locationRepository.getAllLocations()
}

fun insertLocation(location: Location) {
    locationRepository
}
}

Solution

  • The error itself self-explanatory , your VM is returning object of type LiveData<List<Location>>,

    instead of passing the locationList(which is livedata) object directly to adapter ,create lambda like below

    private fun getCities() = launch(Dispatchers.Main) {
        var locationList = addLocationViewModel.location.await()
        locationList.observe(this@AddLocationActivity, Observer { 
            locList -> viewAdapter = LocationAdapter(locList, this)
        })
    }