mengmeng
mengmeng

Reputation: 1506

Async and RecyclerView to display list while fetching data

I'm new to Android. I'm having a problem with displaying the list items in the RecyclerView.

I was hoping to display the list one by one and append while it is still loading. But what happens is, the list will appear after all the items are fetched.

Here is my Fragment

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_lock_list, container, false)
        val recyclerView = view.findViewById<RecyclerView>(R.id.list)

        for(device in devices) {
            fetchBuildingAddress(device)
        }

        if (recyclerView is RecyclerView) {
            with(recyclerView) {
                layoutManager = LinearLayoutManager(context)
                adapter = deviceRecyclerViewAdapter
            }
        }

        return view
    }


    private fun fetchBuildingAddress(device: Device) {
        deviceWearableService.getBuilding(device.buildingId) {
            when(it) {
                is DeviceWearableServiceImpl.State.Success -> {
                    val buildingName = it.resources.buildingAddress.address1

                    val deviceBuilding = DeviceBuillding(device, buildingName)
                    deviceRecyclerViewAdapter.insertDevice(deviceBuilding)
                }
            else -> {
                    // TODO: ERROR STATE
                }
            }

        }

    }

And in my insertDevice I simply call the notifyItemInserted in the adapter.

fun insertDevice(updateDeviceBuilding: DeviceBuillding) {
    deviceBuilding.add(updateDeviceBuilding)
    notifyItemInserted(deviceBuilding.size - 1 )
}

I would also be interested in any better approaches.

Upvotes: 0

Views: 291

Answers (1)

Anshul
Anshul

Reputation: 1659

It's unclear that you are fetching paged data or complete data , but what you need is to use flow with a Diff callback in your adapter i.e PagingDataAdapter(example) or ListAdatper(example).

Its implementation is quite easy you can find it on net.

Upvotes: 0

Related Questions