科特林通过id在LiveData中查找对象

时间:2019-02-05 16:55:57

标签: android kotlin android-livedata

我是科特林的新生。我有一个用户对象列表的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()
    }
}

非常感谢您

0 个答案:

没有答案