Home > Blockchain >  RecyclerView select items loaded from LiveData observe
RecyclerView select items loaded from LiveData observe

Time:03-25

I have a LiveData from my ViewModel that are loaded from the Room Database and after a transformation i display it in a RecyclerView. What i want is to have the select functionality.

ShareViewModel class

val serverConnections: LiveData<List<ShareConnectionModelUi>> = 
    Transformations.map(shareManager.serverWithAccounts) {
        // Here **it**, which is a Map<Server, List<Account>> gets transformed into a list
        // of ShareConnectionModelUi

        // e.g. Map of 
        // Server1, [Account1, Account11]
        // Server2, [Account2, Account22]
        // will be transformed to 
        // [Server1, Account1, Account11, Server2, Account2, Account22 ...]
    }


// The UiModel
sealed class ShareConnectionModelUi {
    class ServerItem(val server: Server): ShareConnectionModelUi()
    class ConnectionItem(val connectionItem: Account, var checked: Boolean): ShareConnectionModelUi()
}

In the Fragment i observe the LiveData and pass it to the RecyclerAdapter, who by the ViewType presents the relative layout. So when the Layout is ShareConnectionModelUi.ConnectionItem, i want the user to be able to check or uncheck the item by clicking on it. I use an interface to the ConnectionItem layout. However, how can i update the LiveData in order to display the checkImage to the ConnectionItemLayout since the visibility of the checkImg is through the ShareConnectionModelUI.ConnectionItem.check??

I guess that i have to update the LiveData. Here is a trial function inside the Viewmodel, which did not work...

fun selectConnection(account: Account) {
        serverConnections.value?.let {
            it.find { s ->
                s is ShareConnectionModelUi.ConnectionItem
                        && s.connectionItem.serverId == account.serverId
                        && s.connectionItem.accountId == account.accountId
            }?.let { s ->
                (s as ShareConnectionModelUi.ConnectionItem).checked == checked
            }
        }
    }

CodePudding user response:

The result of this comparison is unused:

(s as ShareConnectionModelUi.ConnectionItem).checked == checked

Should this be an assignment instead?

(s as ShareConnectionModelUi.ConnectionItem).checked = checked
  • Related