Wednesday, 27 November 2019

How to check changing collection?

Depending on the number of items in the collection, I want to do certain actions.

For example

if i have 1 item in collection -> doFirstAction()
if i have 2 or more items in collection -> doSecondAction()
if i have 2 or more items in collection and deleted all instead one -> doSecondAction()

On this basis i need to check changing the list.

I found something similar: ObservableList. And it seems to solve my problem, but unfortunately I do not know how it can be used correctly.

In my class i need check this collection:

var viewModels: List<ConnectionViewModel> = emptyList()

UPDATE: With this answer i write smth like this:

var viewModels: ObservableList<ConnectionViewModel> = ObservableArrayList<ConnectionViewModel>()

And add listener on my collection:

fun setOnDataChange() {
    viewModels.addOnListChangedCallback(object :
        ObservableList.OnListChangedCallback<ObservableList<ConnectionViewModel>>() {
        override fun onChanged(sender: ObservableList<ConnectionViewModel>?) {}

        override fun onItemRangeRemoved(
            sender: ObservableList<ConnectionViewModel>?,
            positionStart: Int,
            itemCount: Int
        ) {
            showBiometricConfirmation = showConfirmation(itemCount)
        }

        override fun onItemRangeMoved(
            sender: ObservableList<ConnectionViewModel>?,
            fromPosition: Int,
            toPosition: Int,
            itemCount: Int
        ) {}

        override fun onItemRangeInserted(
            sender: ObservableList<ConnectionViewModel>?,
            positionStart: Int,
            itemCount: Int
        ) {
            showBiometricConfirmation = showConfirmation(itemCount)
        }

        override fun onItemRangeChanged(
            sender: ObservableList<ConnectionViewModel>?,
            positionStart: Int,
            itemCount: Int
        ) {}
    })
}

private fun showConfirmation(itemCount: Int): Boolean {
    return itemCount != 1
}

But i have some problem I need check the number in the collection. If number was 3 and after i delete 2, i also need to call doSecondAction(). but if collection number was 1, need to call doFirstAction()



from How to check changing collection?

No comments:

Post a Comment