RecyclerView select 从 LiveData 加载的项目观察

RecyclerView select items loaded from LiveData observe

我有一个来自我的 ViewModel 的 LiveData,它是从 Room 数据库加载的,经过转换后我将它显示在 RecyclerView 中。我想要的是 select 功能。

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()
}

在 Fragment 中,我观察 LiveData 并将其传递给 RecyclerAdapter,后者通过 ViewType 呈现相关布局。因此,当布局为 ShareConnectionModelUi.ConnectionItem 时,我希望用户能够通过单击来选中或取消选中该项目。我使用 ConnectionItem 布局的接口。但是,我如何更新 LiveData 以便将 checkImage 显示到 ConnectionItemLayout,因为 checkImg 的可见性是通过 ShareConnectionModelUI.ConnectionItem.check??

我想我必须更新 LiveData。这是 Viewmodel 中的一个试用函数,它不起作用...

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
            }
        }
    }

此比较结果未使用:

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

这应该是一项作业吗?

(s as ShareConnectionModelUi.ConnectionItem).checked = checked