Should Android listView adapter have api calls

410 Views Asked by At

Hi I have a adapter which displays the list of items and all the functions related to setItems, getCount, notifyDataSetChanged.

adapter also has calls to api's through use cases.

Structure is

Adapter -> UseCase -> Repository -> apiLayer

I am aware that fragemnts and activities should not contains calls to api (usecases in my instance).

So should adapter's have api calls (usecases in my instance)

Thanks R

1

There are 1 best solutions below

0
ChristianB On BEST ANSWER

It is possible, but from a software design point of view I would not recommend it.

The Adapter's responsibility is to connect your Data with the View and make it available to the ListView/RecyclerView. The Adapter should not have any other dependency (knowledge). This will also make it more robust to changes.

So you should consider that only the Activity/Fragment talks to your Presenter and delegates the results from the Presenter to the Adapter. This will also make (unit) testing (of the Presenter) more easier.

class YourActivity: Activity() {
  private val presenter: YourPresenter = // ...

  override fun onCreate() {
    val adapter: YourAdapter = YourAdapter()
    recyclerView.setAdapter(adapter)

    val data = presenter.getData()
    adapter.submit(data)
  }
}

class YourPresenter(private val useCase: UseCase : Presenter() {
  fun getData(): List<Data> {
    return useCase.fetchData()  
  }
}