我是科特林的新生。我有一个用户对象列表的LiveData,如下所示:
data class User(id: String, userName: String, name: String)
我只需要找到一个用户名为“ xxxx”的对象。我尝试了这段代码:
user = userViewModel.allUsers.value!!.find{ it.userName == userName}
但这没用
UserViewModel如下:
class UserViewModel(application: Application) : AndroidViewModel(application) {
private var parentJob = Job()
private val coroutineContext: CoroutineContext
get() = parentJob + Dispatchers.Main
private val scope = CoroutineScope(coroutineContext)
private val repository: UserRepository
val allUsers: LiveData<List<User>>
init {
val usersDao = AppDatabase.getDatabase(application, scope).userDao()
repository = UserRepository(usersDao)
allUsers = repository.allUsers
}
fun getByUserName(userName: String) = scope.launch(Dispatchers.IO) {
repository.findUserById(userName)
}
fun insert(user: User) = scope.launch(Dispatchers.IO) {
repository.insert(user)
}
fun update(user: User) = scope.launch(Dispatchers.IO) {
repository.update(user)
}
override fun onCleared() {
super.onCleared()
parentJob.cancel()
}
}
非常感谢您