feat(notifications): Add function to remove nth notification

This commit is contained in:
Peter Vacho 2025-01-04 22:02:18 +01:00
parent bf3b296136
commit 5ba14f2aba
Signed by: school
GPG key ID: 8CFC3837052871B4
2 changed files with 19 additions and 9 deletions

View file

@ -333,15 +333,9 @@ class NotificationsActivity : AppCompatActivity() {
lifecycleScope.launch(Dispatchers.IO) { lifecycleScope.launch(Dispatchers.IO) {
RetrofitClient.notificationsService.deleteNotification(notification.id) RetrofitClient.notificationsService.deleteNotification(notification.id)
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
// Remove the notification & notify the adapter about it // This both notifies the adapter & removes the notification from the
notifications.removeAt(position) // notifications list
adapter.notifyItemRemoved(position) (rvNotifications.adapter as NotificationAdapter).removeNotificationAt(position)
// Annoyingly, we can't just use notifyItemRemoved for the single removed item,
// as all the items below it would now be using the wrong position that was
// already bounded to the callbacks from the click listeners, so we need to refresh
// all of the notifications below this one as well.
adapter.notifyItemRangeChanged(position, notifications.size - position)
Toast.makeText(this@NotificationsActivity, "Notification deleted", Toast.LENGTH_SHORT).show() Toast.makeText(this@NotificationsActivity, "Notification deleted", Toast.LENGTH_SHORT).show()
updateEmptyState() updateEmptyState()

View file

@ -189,4 +189,20 @@ class NotificationAdapter(
else -> DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").format(createdAt) else -> DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").format(createdAt)
} }
} }
/**
* Remove a notification from the list and notify the adapter.
*
* Call this after the callback deletes the notification from the backend API.
*/
fun removeNotificationAt(position: Int) {
notifications.removeAt(position)
notifyItemRemoved(position)
// Annoyingly, we can't just use notifyItemRemoved for the single removed item,
// as all the items below it would now be using the wrong position that was
// already bound to the callbacks from the click listeners, so we need to refresh
// all of the notifications below this one as well.
notifyItemRangeChanged(position, notifications.size - position)
}
} }