@Query("SELECT * FROM InDIve order by seq desc")
fun getAllPlayList() : Flow<List<PlayListEntity>>
DAO에서 Flow로 반환하게 설정
fun getAllPlayList(): Flow<List<PlayListEntity>> = playListDao.getAllPlayList()
DataSource에서는 flow{} 안에서 실행하지 않고 바로 dao 호출
fun getAllPlayList(): Flow<Result<List<PlayListEntity>>> = flow {
emit(Result.Loading)
inDiveLocalDataSource.getAllPlayList().collect {
if (it.isEmpty()) {
emit(Result.Empty)
} else {
emit(Result.Success(it))
}
}
}.catch { e -> emit(Result.Error(e)) }
collectLatest 가 아닌 collect를 사용하여 데이터 가져오기 collectlatest vs collect
Repository에서 들어온 값이 비어있는지 확인하고 비어있으면 Empty를 emit하고 비어있지 않으면 Success를 emit
viewModelScope.launch(Dispatchers.IO) {
playListRepository.getAllPlayList().collectLatest {
if (it is Result.Success) {
_playList.value = it.data
} else if (it is Result.Empty) {
_playList.value = listOf()
} else if (it is Result.Error) {
Log.d("MainViewModel", "getAllError: ${it}")
}
}
}
뷰모델에서 emit된 결과마다 분기하여 처리