所以,我在我的应用程序中有两个ViewModels和两个屏幕。第一个屏幕是用于显示日记项元素列表,第二个屏幕用于显示日记项的详细信息。在第二个ViewModel中,我有一个id从DB获取记录,但可以找到它。我怎么做才能得到它?
DAO:
interface DiaryDao {
@Query("SELECT * FROM diaryItems")
fun getAllDiaryPosts(): LiveData<List<DiaryItem>>
@Query("Select * from diaryItems where id = :id")
fun getDiaryPostById(id: Int) : DiaryItem
@Query("Delete from diaryItems where id = :index")
fun deleteDiaryPostByIndex(index : Int)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertDiaryPost(diaryItem: DiaryItem)
@Update
suspend fun updateDiaryPost(diaryItem: DiaryItem)
@Delete
suspend fun deleteDiaryPost(diaryItem: DiaryItem)
@Query("Delete from diaryItems")
suspend fun deleteAllDiaryItems()
}
库
class DiaryRepository @Inject constructor(private val diaryDao: DiaryDao) {
val readAllData: LiveData<List<DiaryItem>> = diaryDao.getAllDiaryPosts()
suspend fun getDiaryPostDyIndex(index: Int): DiaryItem {
return diaryDao.getDiaryPostById(index)
}
}
第一viewmodel
@HiltViewModel
class PostListViewModel
@Inject
constructor(
private val diaryRepository: DiaryRepository,
) : ViewModel() {
private var allDiaryItems: LiveData<List<DiaryItem>> = diaryRepository.readAllData
}
第二viewmodel
@HiltViewModel
class PostDetailViewModel
@Inject
constructor(
private val savedStateHandle: SavedStateHandle,
private val diaryRepository: DiaryRepository
) : ViewModel() {
sealed class UIState {
object Loading: UIState()
data class Success(val currentPosts: DiaryItem) : UIState()
object Error : UIState()
}
val postDetailState: State<UIState>
get() = _postDetailState
private val _postDetailState = mutableStateOf<UIState>(UIState.Loading)
init {
viewModelScope.launch (Dispatchers.IO) {
try {
val diaryList: DiaryItem = diaryRepository.getDiaryPostDyIndex(2) //it is for test
_postDetailState.value = UIState.Success(diaryList)
} catch (e: Exception) {
withContext(Dispatchers.Main) {
_postDetailState.value = UIState.Error
}
}
}
}
}
我肯定你得到错误。因为你更新UI状态在IO线程
fun getDairyItem(itemId: Int){
viewModelScope.launch (Dispatchers.IO) {
try {
val diaryList: DiaryItem = diaryRepository.getDiaryPostDyIndex(itemId)
withContext(Dispatchers.Main) {
_postDetailState.value = UIState.Success(diaryList)
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
_postDetailState.value = UIState.Error
}
}
}
}