1

Let's say that there is a simple scenario:

  • user table for storing user details
  • user_images to store in a image_path field the paths of images in the phone's storage.

There is a list of users shown in a RecyclerView and the user can Swipe to delete a row. The adapter is a ListAdapter and the data comes from Room as being LiveData

Workflow I was thinking is like this:

  1. remove the swiped item from the adapter and update the recyclerview
  2. show a Snack with Undo option
  3. on Snack if user presses Undo, re-add the item in the ListAdapter and update the recyclerview. If the user does not press Undo and the Snack gets dismissed after timeout, delete the rows from user, user_images and also delete all the images from the storage related to user_images in image_path

...

override fun onSwiped(...){
  val deletedItem = listAdapter.currentList.get(index)

  //REMOVE FROM THE ADAPTER HERE

  val snack = Snackbar.make(...)
  snack.setAction(...){
      //RE-ADD TO ADAPTER HERE
  }

  snack.addCallback(...){
    override fun onDismissed(...){
       //do the actual deletes
    }
  }

}

...

The issue is using the ListAdapter. As you may know it uses DiffCallBack to manage the view updates and calling adapter.submitList(list) does not trigger any updates as it receives the same list. (ListAdapter not updating item in reyclerview) So in order to be able to remove item, I would need to:

  • get the adapter's currentList as Mutable updatebleList
  • remove the item from the updatebleList
  • re-submit the list to the adapter adapter.submitList(updatebleList.toList())
  • in case of Undo, re-add the item to the updatebleListand submit it again as a new list adapter.submitList(updatebleList.toList())

As you see, there are a lot of list re-creation in order to properly submit. Is there a better/simpler way to achieve this?

Alin
  • 14,809
  • 40
  • 129
  • 218
  • You should have an intermediate representation of your data, containing the deletion state. Because managing that in the activity/fragment is not the place to perform that. – Rajar Feb 06 '19 at 14:40
  • 1
    you need to remove it from database table anyway.. and then insert it again, and then everything automatically re-appears (LiveData from Database Query and sumbit func of RecyclerView) – user924 Oct 02 '19 at 22:09

1 Answers1

1

I have simply apply swipe to delete functionality in MainActivity via creating new ItemTouchHelper(). You can check the sample code on GitHub here.

Ercan
  • 2,601
  • 22
  • 23