Skip to content

Commit

Permalink
Merge branch 'develop' into feature/#202
Browse files Browse the repository at this point in the history
  • Loading branch information
TRASALBY committed Dec 12, 2022
2 parents c70977e + 6ab72a1 commit 0ef93a1
Show file tree
Hide file tree
Showing 7 changed files with 211 additions and 121 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ import com.lateinit.rightweight.data.model.remote.StructuredQueryData
import com.lateinit.rightweight.data.remote.model.IntValue
import com.lateinit.rightweight.data.remote.model.TimeStampValue
import kotlinx.coroutines.flow.first
import retrofit2.HttpException
import java.io.IOException

@OptIn(ExperimentalPagingApi::class)
class SharedRoutineRemoteMediator(
Expand All @@ -41,96 +39,90 @@ class SharedRoutineRemoteMediator(
loadType: LoadType,
state: PagingState<Int, SharedRoutine>
): MediatorResult {
try {
var endOfPaginationReached = false
var endOfPaginationReached = false

var pagingFlag = when (loadType) {
LoadType.REFRESH -> "$INIT_MODIFIED_DATE_FLAG/$INIT_SHARED_COUNT_FLAG"
LoadType.PREPEND -> {
endOfPaginationReached = true
return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
}
LoadType.APPEND -> {
val flag = appPreferencesDataStore.sharedRoutinePagingFlag.first()
flag.ifEmpty { "$INIT_MODIFIED_DATE_FLAG/$INIT_SHARED_COUNT_FLAG" }
}
var pagingFlag = when (loadType) {
LoadType.REFRESH -> "$INIT_MODIFIED_DATE_FLAG/$INIT_SHARED_COUNT_FLAG"
LoadType.PREPEND -> {
endOfPaginationReached = true
return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
}
LoadType.APPEND -> {
val flag = appPreferencesDataStore.sharedRoutinePagingFlag.first()
flag.ifEmpty { "$INIT_MODIFIED_DATE_FLAG/$INIT_SHARED_COUNT_FLAG" }
}
}

val splitedPagingFlag = pagingFlag.split("/")
var modifiedDateFlag = splitedPagingFlag[0]
var sharedCountFlag = splitedPagingFlag[1]
val splitedPagingFlag = pagingFlag.split("/")
var modifiedDateFlag = splitedPagingFlag[0]
var sharedCountFlag = splitedPagingFlag[1]

when (sortType) {
SharedRoutineSortType.MODIFIED_DATE_FIRST -> {
runQueryBody = RunQueryBody(
StructuredQueryData(
from = FromData("shared_routine"),
orderBy = listOf(
OrderByData(FiledReferenceData("modified_date"), "DESCENDING"),
OrderByData(FiledReferenceData("shared_count.count"), "DESCENDING")
),
limit = 10,
startAt = StartAtData(
listOf(
TimeStampValue(modifiedDateFlag),
IntValue(sharedCountFlag)
)
when (sortType) {
SharedRoutineSortType.MODIFIED_DATE_FIRST -> {
runQueryBody = RunQueryBody(
StructuredQueryData(
from = FromData("shared_routine"),
orderBy = listOf(
OrderByData(FiledReferenceData("modified_date"), "DESCENDING"),
OrderByData(FiledReferenceData("shared_count.count"), "DESCENDING")
),
limit = 10,
startAt = StartAtData(
listOf(
TimeStampValue(modifiedDateFlag),
IntValue(sharedCountFlag)
)
)
)
}
SharedRoutineSortType.SHARED_COUNT_FIRST -> {
runQueryBody = RunQueryBody(
StructuredQueryData(
FromData("shared_routine"),
orderBy = listOf(
OrderByData(FiledReferenceData("shared_count.count"), "DESCENDING"),
OrderByData(FiledReferenceData("modified_date"), "DESCENDING")
),
limit = 10,
startAt = StartAtData(
listOf(
IntValue(sharedCountFlag),
TimeStampValue(modifiedDateFlag)
)
)
}
SharedRoutineSortType.SHARED_COUNT_FIRST -> {
runQueryBody = RunQueryBody(
StructuredQueryData(
FromData("shared_routine"),
orderBy = listOf(
OrderByData(FiledReferenceData("shared_count.count"), "DESCENDING"),
OrderByData(FiledReferenceData("modified_date"), "DESCENDING")
),
limit = 10,
startAt = StartAtData(
listOf(
IntValue(sharedCountFlag),
TimeStampValue(modifiedDateFlag)
)
)
)
}
)
}
}

val documentResponses = api.getSharedRoutines(
runQueryBody
)
val documentResponses = api.getSharedRoutines(
runQueryBody
)

db.withTransaction {
if (loadType == LoadType.REFRESH) {
appPreferencesDataStore.saveSharedRoutinePagingFlag("$INIT_MODIFIED_DATE_FLAG/$INIT_SHARED_COUNT_FLAG")
db.sharedRoutineDao().removeAllSharedRoutines()
}
db.withTransaction {
if (loadType == LoadType.REFRESH) {
appPreferencesDataStore.saveSharedRoutinePagingFlag("$INIT_MODIFIED_DATE_FLAG/$INIT_SHARED_COUNT_FLAG")
db.sharedRoutineDao().removeAllSharedRoutines()
}

documentResponses.forEach { documentResponse ->
if (documentResponse.document != null) {
db.sharedRoutineDao()
.insertSharedRoutine(documentResponse.document.toSharedRoutine())
modifiedDateFlag =
documentResponse.document.fields.modifiedDate.value
sharedCountFlag =
documentResponse.document.fields.sharedCount.value.remoteData.count.value
pagingFlag = "$modifiedDateFlag/$sharedCountFlag"
} else {
endOfPaginationReached = true
}
documentResponses.forEach { documentResponse ->
if (documentResponse.document != null) {
db.sharedRoutineDao()
.insertSharedRoutine(documentResponse.document.toSharedRoutine())
modifiedDateFlag =
documentResponse.document.fields.modifiedDate.value
sharedCountFlag =
documentResponse.document.fields.sharedCount.value.remoteData.count.value
pagingFlag = "$modifiedDateFlag/$sharedCountFlag"
} else {
endOfPaginationReached = true
}
appPreferencesDataStore.saveSharedRoutinePagingFlag(pagingFlag)
}

return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
} catch (e: IOException) {
return MediatorResult.Error(e)
} catch (e: HttpException) {
return MediatorResult.Error(e)
appPreferencesDataStore.saveSharedRoutinePagingFlag(pagingFlag)
}

return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,15 @@ class SharedRoutineFragment : Fragment(), SharedRoutineClickHandler {
is LatestSharedRoutineUiState.Success -> {
sharedRoutinePagingAdapter.submitData(uiState.sharedRoutines)
}
is LatestSharedRoutineUiState.Error -> Exception()
is LatestSharedRoutineUiState.Error -> {
Snackbar.make(
binding.root,
R.string.wrong_connection,
Snackbar.LENGTH_LONG
).apply {
anchorView = binding.guideLineBottom
}.show()
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,61 @@ import androidx.paging.cachedIn
import androidx.paging.map
import com.lateinit.rightweight.data.mapper.local.toSharedRoutineSortType
import com.lateinit.rightweight.data.repository.SharedRoutineRepository
import com.lateinit.rightweight.ui.login.NetworkState
import com.lateinit.rightweight.ui.mapper.toSharedRoutineUiModel
import com.lateinit.rightweight.ui.model.shared.SharedRoutineSortTypeUiModel
import com.lateinit.rightweight.ui.model.shared.SharedRoutineUiModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import retrofit2.HttpException
import java.net.SocketException
import java.net.UnknownHostException
import javax.inject.Inject

@HiltViewModel
class SharedRoutineViewModel @Inject constructor(
private val sharedRoutineRepository: SharedRoutineRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(LatestSharedRoutineUiState.Success(PagingData.empty()))
private val _uiState =
MutableStateFlow<LatestSharedRoutineUiState>(LatestSharedRoutineUiState.Success(PagingData.empty()))
val uiState: StateFlow<LatestSharedRoutineUiState> = _uiState

val networkExceptionHandler = CoroutineExceptionHandler { _, throwable ->
when (throwable) {
is SocketException -> sendNetworkResultEvent(NetworkState.BAD_INTERNET)
is HttpException -> sendNetworkResultEvent(NetworkState.PARSE_ERROR)
is UnknownHostException -> sendNetworkResultEvent(NetworkState.WRONG_CONNECTION)
else -> sendNetworkResultEvent(NetworkState.OTHER_ERROR)
}
}

init {
getSharedRoutinesByPaging()
}

private fun sendNetworkResultEvent(state: NetworkState) {
viewModelScope.launch {
sharedRoutineRepository.getSharedRoutinesByPaging().cachedIn(this).collect{ sharedRoutinePagingData ->
val sharedRoutines = sharedRoutinePagingData.map { sharedRoutine ->
sharedRoutine.toSharedRoutineUiModel()
_uiState.value = LatestSharedRoutineUiState.Error(state)
}
}

private fun getSharedRoutinesByPaging() {
viewModelScope.launch(networkExceptionHandler) {
sharedRoutineRepository.getSharedRoutinesByPaging().cachedIn(this)
.collect { sharedRoutinePagingData ->
val sharedRoutines = sharedRoutinePagingData.map { sharedRoutine ->
sharedRoutine.toSharedRoutineUiModel()
}
_uiState.value = LatestSharedRoutineUiState.Success(sharedRoutines)
}
_uiState.value = LatestSharedRoutineUiState.Success(sharedRoutines)
}
}
}

fun setSharedRoutineSortType(sortTypeUiModel: SharedRoutineSortTypeUiModel){
fun setSharedRoutineSortType(sortTypeUiModel: SharedRoutineSortTypeUiModel) {
getSharedRoutinesByPaging()
viewModelScope.launch {
sharedRoutineRepository.setSharedRoutineSortType(sortTypeUiModel.toSharedRoutineSortType())
}
Expand All @@ -46,5 +73,5 @@ sealed class LatestSharedRoutineUiState {
data class Success(val sharedRoutines: PagingData<SharedRoutineUiModel>) :
LatestSharedRoutineUiState()

data class Error(val exception: Throwable) : LatestSharedRoutineUiState()
}
data class Error(val state: NetworkState) : LatestSharedRoutineUiState()
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.snackbar.Snackbar
import com.lateinit.rightweight.R
import com.lateinit.rightweight.databinding.FragmentSharedRoutineDetailBinding
import com.lateinit.rightweight.ui.model.routine.DayUiModel
import com.lateinit.rightweight.ui.routine.detail.DetailExerciseAdapter
Expand Down Expand Up @@ -48,6 +50,7 @@ class SharedRoutineDetailFragment : Fragment() {
setRoutineDayAdapter()
setExerciseAdapter()
setSharedRoutineDetailCollect()
setButtonRoutineImportOnClickListener()
handleNavigationEvent()
}

Expand Down Expand Up @@ -80,21 +83,36 @@ class SharedRoutineDetailFragment : Fragment() {
binding.sharedRoutineUiModel = uiState.sharedRoutineUiModel
routineDayAdapter.submitList(uiState.dayUiModels)
setCurrentDayPositionObserve(uiState.dayUiModels)

binding.buttonRoutineImport.setOnClickListener {
viewModel.importSharedRoutineToMyRoutines(
uiState.sharedRoutineUiModel,
uiState.dayUiModels
)

}
}
is LatestSharedRoutineDetailUiState.Error -> Exception()
is LatestSharedRoutineDetailUiState.Error -> {
Snackbar.make(
binding.root,
R.string.wrong_connection,
Snackbar.LENGTH_LONG
).apply {
anchorView = binding.guideLineBottom
}.show()
findNavController().navigateUp()
}
}
}
}
}

private fun setButtonRoutineImportOnClickListener() {
binding.buttonRoutineImport.setOnClickListener {
if (viewModel.importSharedRoutineToMyRoutines().not()) {
Snackbar.make(
binding.root,
R.string.none_routine,
Snackbar.LENGTH_LONG
).apply {
anchorView = binding.guideLineBottom
}.show()
}
}
}

private fun setCurrentDayPositionObserve(dayUiModels: List<DayUiModel>) {
viewModel.currentDayPosition.observe(viewLifecycleOwner) {
if (dayUiModels.size > it) {
Expand All @@ -106,7 +124,7 @@ class SharedRoutineDetailFragment : Fragment() {

private fun handleNavigationEvent() {
viewLifecycleOwner.collectOnLifecycle {
viewModel.navigationEvent.collect {
viewModel.navigationEvent.collect {
setFragmentResult("routineCopy", bundleOf())
findNavController().navigateUp()
}
Expand Down
Loading

0 comments on commit 0ef93a1

Please sign in to comment.