Skip to content

Commit

Permalink
#25 refactor: 일지 불러오기 Paging -> Flow로 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
SeungWoo-Ahn committed Apr 18, 2024
1 parent 30e63bd commit 0242756
Show file tree
Hide file tree
Showing 8 changed files with 57 additions and 82 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package io.tuttut.data.repository.diary

import androidx.paging.PagingData
import com.google.firebase.firestore.DocumentReference
import io.tuttut.data.model.dto.Diary
import kotlinx.coroutines.flow.Flow
import io.tuttut.data.model.response.Result

interface DiaryRepository {
fun getDiaryList(gardenId: String, cropsId: String): Flow<PagingData<Diary>>

fun getFourDiaryList(gardenId: String, cropsId: String): Flow<List<Diary>>
fun getDiaryList(gardenId: String, cropsId: String): Flow<List<Diary>>

fun getDiaryDetail(gardenId: String, diaryId: String): Flow<Diary>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package io.tuttut.data.repository.diary

import androidx.paging.PagingData
import com.google.firebase.Firebase
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.DocumentReference
Expand All @@ -13,37 +12,24 @@ import io.tuttut.data.model.dto.toMap
import io.tuttut.data.model.response.Result
import io.tuttut.data.util.asFlow
import io.tuttut.data.util.asSnapShotFlow
import io.tuttut.data.util.providePager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
import javax.inject.Named

class DiaryRepositoryImpl @Inject constructor(
@Named("gardensRef") val gardenRef: CollectionReference
) : DiaryRepository {
override fun getDiaryList(gardenId: String, cropsId: String): Flow<PagingData<Diary>>
= providePager(
pageSize = 8,
dataType = Diary::class.java,
query = gardenRef.document(gardenId)
override fun getDiaryList(gardenId: String, cropsId: String): Flow<List<Diary>>
= gardenRef.document(gardenId)
.collection(FireBaseKey.DIARY)
.whereEqualTo(FireBaseKey.DIARY_KEY, cropsId)
.orderBy(FireBaseKey.DIARY_CREATED, Query.Direction.DESCENDING)
)

override fun getFourDiaryList(gardenId: String, cropsId: String): Flow<List<Diary>>
= gardenRef.document(gardenId)
.collection(FireBaseKey.DIARY)
.whereEqualTo(FireBaseKey.DIARY_KEY, cropsId)
.orderBy(FireBaseKey.DIARY_CREATED, Query.Direction.DESCENDING)
.asFlow(Diary::class.java)
.take(4)
.asFlow(Diary::class.java)

override fun getDiaryDetail(gardenId: String, diaryId: String): Flow<Diary>
= gardenRef.document(gardenId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,11 @@ import javax.inject.Singleton

@Singleton
class DiaryModel @Inject constructor() {
val refreshDiaryList = MutableStateFlow(false)

private val _observedDiary = MutableStateFlow(Diary())
val observedDiary: StateFlow<Diary> = _observedDiary
private val _diaryEditMode = MutableStateFlow(false)
val diaryEditMode: StateFlow<Boolean> = _diaryEditMode

fun refreshDiaryList() {
refreshDiaryList.value = true
}

fun observeDiary(
diary: Diary,
editMode: Boolean = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.launch
import javax.inject.Inject

Expand Down Expand Up @@ -51,10 +52,10 @@ class CropsDetailViewModel @Inject constructor(
)

val diaryUiState: StateFlow<CropsDiaryUiState>
= diaryRepo.getFourDiaryList(
= diaryRepo.getDiaryList(
gardenId = gardenId,
cropsId = crops.id
).map(CropsDiaryUiState::Success)
).take(4).map(CropsDiaryUiState::Success)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ class DiaryDetailViewModel @Inject constructor(
}
is Result.Success -> {
refresh()
diaryModel.refreshDiaryList()
_typedComment.value = ""
}
else -> {}
Expand All @@ -106,7 +105,6 @@ class DiaryDetailViewModel @Inject constructor(
when (it) {
is Result.Error -> onShowSnackBar("일지 삭제에 실패했어요", null)
is Result.Success -> {
diaryModel.refreshDiaryList()
moveBack()
onShowSnackBar("일지를 삭제했어요", null)
}
Expand All @@ -133,7 +131,6 @@ class DiaryDetailViewModel @Inject constructor(
when (it) {
is Result.Error -> onShowSnackBar("댓글 삭제에 실패했어요", null)
is Result.Success -> {
diaryModel.refreshDiaryList()
refresh()
}
else -> {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
Expand All @@ -28,10 +28,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import io.tuttut.data.constant.DEFAULT_MAIN_IMAGE
import io.tuttut.data.model.dto.Diary
import io.tuttut.data.model.dto.User
Expand All @@ -56,15 +53,12 @@ fun DiaryListRoute(
onShowSnackBar: suspend (String, String?) -> Boolean,
viewModel: DiaryListViewModel = hiltViewModel()
) {
val diaryList = viewModel.diaryList.collectAsLazyPagingItems()
LaunchedEffect(Unit) {
viewModel.refreshDiaryList(diaryList)
}
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
DiaryListScreen(
modifier = modifier,
uiState = uiState,
cropsName = viewModel.crops.nickName,
userId = viewModel.currentUser.id,
diaryList = diaryList,
memberMap = viewModel.memberMap,
onDiary = { viewModel.onDiary(it, moveDiary) },
onEdit = { viewModel.onEdit(it, moveEditDiary) },
Expand All @@ -75,7 +69,7 @@ fun DiaryListRoute(
NegativeBottomSheet(
showSheet = viewModel.showDeleteSheet,
scope = scope,
onButton = { viewModel.onDelete(diaryList, onShowSnackBar) },
onButton = { viewModel.onDelete(onShowSnackBar) },
onDismissRequest = { viewModel.showDeleteSheet = false }
)
ReportBottomSheet(
Expand All @@ -90,9 +84,9 @@ fun DiaryListRoute(
@Composable
internal fun DiaryListScreen(
modifier: Modifier,
uiState: DiaryListUiState,
cropsName: String,
userId: String,
diaryList: LazyPagingItems<Diary>,
memberMap: HashMap<String, User>,
onDiary: (Diary) -> Unit,
onEdit: (Diary) -> Unit,
Expand All @@ -107,35 +101,31 @@ internal fun DiaryListScreen(
title = "$cropsName ${stringResource(id = R.string.diary_name)}",
onBack = onBack
)
when (diaryList.loadState.refresh) {
LoadState.Loading -> TutTutLoadingScreen()
else -> {
when (uiState) {
DiaryListUiState.Loading -> TutTutLoadingScreen()
is DiaryListUiState.Success -> {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = screenHorizontalPadding),
state = rememberLazyListState()
) {
items(
count = diaryList.itemCount,
key = diaryList.itemKey { it.id }
) { index ->
diaryList[index]?.let { diary ->
DiaryItem(
isMine = diary.authorId == userId || memberMap[diary.authorId] == null,
diary = diary,
memberMap = memberMap,
onEdit = { onEdit(diary) },
onDelete = { onDelete(diary) },
onReport = onReport,
onClick = { onDiary(diary) }
)
}
items = uiState.diaryList,
key = { it.id }
) { diary ->
DiaryItem(
isMine = diary.authorId == userId || memberMap[diary.authorId] == null,
diary = diary,
memberMap = memberMap,
onEdit = { onEdit(diary) },
onDelete = { onDelete(diary) },
onReport = onReport,
onClick = { onDiary(diary) }
)
}
}
}
}

}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package io.tuttut.presentation.ui.screen.main.diaryList

import io.tuttut.data.model.dto.Diary

sealed interface DiaryListUiState {
data object Loading : DiaryListUiState
data class Success(
val diaryList: List<Diary>
) : DiaryListUiState
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.compose.LazyPagingItems
import dagger.hilt.android.lifecycle.HiltViewModel
import io.tuttut.data.model.dto.Diary
import io.tuttut.data.model.response.Result
Expand All @@ -19,7 +16,10 @@ import io.tuttut.presentation.base.BaseViewModel
import io.tuttut.presentation.model.CropsModel
import io.tuttut.presentation.model.DiaryModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
Expand All @@ -34,11 +34,18 @@ class DiaryListViewModel @Inject constructor(
private val diaryModel: DiaryModel,
cropsModel: CropsModel,
) : BaseViewModel() {
val crops = cropsModel.observedCrops.value
val currentUser = authRepo.currentUser.value
val crops = cropsModel.observedCrops.value
val memberMap = gardenRepo.gardenMemberMap

val diaryList: Flow<PagingData<Diary>> = diaryRepo.getDiaryList(currentUser.gardenId, crops.id).cachedIn(viewModelScope)
val uiState: StateFlow<DiaryListUiState>
= diaryRepo.getDiaryList(currentUser.gardenId, crops.id)
.map(DiaryListUiState::Success)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = DiaryListUiState.Loading
)

private var selectedDiary by mutableStateOf(Diary())
var showDeleteSheet by mutableStateOf(false)
Expand All @@ -59,21 +66,20 @@ class DiaryListViewModel @Inject constructor(
showDeleteSheet = true
}

fun onDelete(diaryList: LazyPagingItems<Diary>, onShowSnackBar: suspend (String, String?) -> Boolean) {
fun onDelete(onShowSnackBar: suspend (String, String?) -> Boolean) {
viewModelScope.launch {
diaryRepo.deleteDiary(currentUser.gardenId, selectedDiary).collect {
when (it) {
is Result.Error -> onShowSnackBar("일지 삭제에 실패했어요", null)
is Result.Success -> {
diaryList.refresh()
withContext(Dispatchers.IO) {
commentRepo.deleteAllDiaryComments(currentUser.gardenId, selectedDiary.id)
storageRepo.deleteAllImages(selectedDiary.imgUrlList)
}
}
else -> {}
}
}
withContext(Dispatchers.IO) {
commentRepo.deleteAllDiaryComments(currentUser.gardenId, selectedDiary.id)
storageRepo.deleteAllImages(selectedDiary.imgUrlList)
}
}
}

Expand All @@ -83,10 +89,4 @@ class DiaryListViewModel @Inject constructor(
onShowSnackBar("${reason}로 신고했어요", null)
}
}

fun refreshDiaryList(diaryList: LazyPagingItems<Diary>) {
useFlag(diaryModel.refreshDiaryList) {
diaryList.refresh()
}
}
}

0 comments on commit 0242756

Please sign in to comment.