Home > Enterprise >  How to implement a File-Upload from an Adapter in Android using MVVM?
How to implement a File-Upload from an Adapter in Android using MVVM?

Time:03-09

I develop an Android-App which has a RecyclerView, each item displayed in the RecyclerView represents a video saved locally. Now, when a button is clicked in one of the items in the RecyclerView, the file should be uploaded to a server. Now my question: How can I implement a solution to do this using MVVM?

I also created a little image which describes my problem:

Image describing the problem

Note: A short, conceptual answeser is sufficient

CodePudding user response:

your adapter takes in a callback method to invoke once the button is tapped, the fragment then does this upload by using the VM, once that is done, success or failure you alert your UI to make whatever changes are needed. there's no interaction between your viewmodel and your adapter directly

class MyAdapter constructor(
    private val callback: (item: YourType) -> Unit,
) : RecyclerView.Adapter.... {

then, you would call this in onBind or wherever you're setting up your button for the adapter, by calling:

 myButton.setOnClickListener {
 callback.invoke(yourItem)
 }

usually this is in the format of:

override fun onBindViewHolder(holder: SomeViewHolder, position: Int) {
    val yourItem: YourType = items[position]
    ....

    yourButton.setOnClickListener {
        callback.invoke(yourItem)
    }
}

when you create your adapter, you now do:

myAdapter = MyAdapter () { callback ->
 //here, callback will be of type `YourType`
 //here, you can do whatever service call you want with your viewmodel, because this is in your fragment
}

In summary, the logic for what has to happen when an item is tapped is now shifted on to the class making use of the adapter, usually the fragment or the activity. This makes it so that you can easily reuse your adapter, because it doesn't contain any actual business logic inside of it - your adapter basically informs your fragment that: "something was tapped, here's the corresponding item".

Your adapter notifies your fragment that an item was tapped, your fragment can then decide what to do, in this case it can shift this along to the Viewmodel so that it can then perform any network operation you need and inform the UI of the result of that operation, usually this is done by observing on to live data

  • Related