Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil3.compose.AsyncImage
import com.afternote.core.ui.theme.AfternoteDesign
Expand All @@ -55,6 +57,10 @@ fun RecipientTimeLetterDetailScreen(
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()

LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
viewModel.refreshOnReturn()
}

Scaffold(
modifier = modifier,
topBar = { DetailTopBar(title = "타임레터", onBackClick = onBackClick) },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.afternote.core.ui.calendar.CalendarGridContent
import com.afternote.core.ui.theme.AfternoteDesign
Expand All @@ -56,6 +58,10 @@ fun RecipientTimeletterScreen(
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()

LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
viewModel.refreshOnReturn()
}

var currentYear by remember { mutableIntStateOf(LocalDate.now().year) }
var currentMonth by remember { mutableIntStateOf(LocalDate.now().monthValue) }
var selectedDate by remember { mutableStateOf(LocalDate.now()) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.afternote.core.ui.button.AfternoteButton
import com.afternote.core.ui.button.AfternoteButtonType
Expand Down Expand Up @@ -63,6 +65,10 @@ fun DraftLetterScreen(
}
}

LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
viewModel.refreshOnReturn()
}

DraftLetterContent(
uiState = uiState,
onBackClick = onBackClick,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.afternote.core.common.util.KoreanConsonantUtil
import com.afternote.core.model.setting.ReceiverListItem
Expand All @@ -53,6 +55,9 @@ fun RecipientListScreen(
viewModel: RecipientListViewModel = hiltViewModel(),
) {
val recipients by viewModel.recipients.collectAsStateWithLifecycle()
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
viewModel.refreshOnReturn()
}
RecipientListContent(
recipients = recipients,
onBackClick = onBackClick,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil3.compose.AsyncImage
import com.afternote.core.ui.theme.AfternoteDesign
Expand All @@ -55,6 +57,10 @@ fun TimeLetterDetailScreen(
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()

LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
viewModel.refreshOnReturn()
}

Scaffold(
modifier = modifier,
topBar = { DetailTopBar(title = "타임레터", onBackClick = onBackClick) },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import com.afternote.feature.timeletter.domain.repository.TimeLetterRepository
import com.afternote.feature.timeletter.presentation.R
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand All @@ -24,30 +25,62 @@ class DraftLetterViewModel
private val _uiState = MutableStateFlow<DraftLetterUiState>(DraftLetterUiState.Loading)
val uiState: StateFlow<DraftLetterUiState> = _uiState.asStateFlow()

/** 진행 중인 조회 — 첫 진입 이후의 ON_RESUME 이 실행 중인 로드와 겹치면 건너뛰기 위한 가드. */
private var loadJob: Job? = null

/**
* 다음 [refreshOnReturn] 이 첫 ON_RESUME(진입 자체)인지. 첫 resume 은 init 로드와 같은
* 진입이므로 갱신하지 않는다 — VM 필드인 이유는 ReceiverHomeViewModel 의 refreshOnReturn 과
* 동일, 프로세스 사망 후 복원에서도 init 로드와 수명이 일치한다.
*/
private var isFirstResume = true

init {
loadDrafts()
}

fun loadDrafts() {
viewModelScope.launch {
_uiState.value = DraftLetterUiState.Loading
try {
val result = timeLetterRepository.getTemporaryTimeLetters()
val receiverNameMap =
runCatchingCancellable { userRepository.getReceivers() }
.getOrElse { emptyList() }
.associate { receiver -> receiver.receiverId to receiver.name }
_uiState.value =
DraftLetterUiState.Success(
drafts = result.timeLetters,
receiverNameMap = receiverNameMap,
)
} catch (cancellationException: CancellationException) {
throw cancellationException
} catch (_: Exception) {
_uiState.value = DraftLetterUiState.Error(R.string.timeletter_draft_load_error)
}
/**
* 다른 화면에서 복귀했을 때의 자동 갱신 (#701). 최초 진입 로드와 두 가지가 다르다 —
* 로딩을 방출하지 않고, 실패해도 보고 있던 초안 목록을 유지한다.
* 첫 진입은 건너뛰고, 로드가 겹치면 건너뛴다.
*/
fun refreshOnReturn() {
if (isFirstResume) {
isFirstResume = false
return
}
if (loadJob?.isActive == true) return
loadDrafts(showsLoading = false, keepsStateOnFailure = true)
}

fun loadDrafts(
showsLoading: Boolean = true,
keepsStateOnFailure: Boolean = false,
) {
loadJob =
viewModelScope.launch {
if (showsLoading) {
_uiState.value = DraftLetterUiState.Loading
}
try {
val result = timeLetterRepository.getTemporaryTimeLetters()
val receiverNameMap =
runCatchingCancellable { userRepository.getReceivers() }
.getOrElse { emptyList() }
.associate { receiver -> receiver.receiverId to receiver.name }
_uiState.value =
DraftLetterUiState.Success(
drafts = result.timeLetters,
receiverNameMap = receiverNameMap,
)
} catch (cancellationException: CancellationException) {
throw cancellationException
} catch (_: Exception) {
if (!(keepsStateOnFailure && _uiState.value is DraftLetterUiState.Success)) {
_uiState.value = DraftLetterUiState.Error(R.string.timeletter_draft_load_error)
}
}
}
}

fun toggleEditMode() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import androidx.lifecycle.viewModelScope
import com.afternote.core.domain.repository.UserRepository
import com.afternote.core.model.setting.ReceiverListItem
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
Expand All @@ -17,12 +19,38 @@ class RecipientListViewModel
constructor(
private val userRepository: UserRepository,
) : ViewModel() {
private val refreshRequests = MutableStateFlow(0)

val recipients: StateFlow<List<ReceiverListItem>> =
userRepository.receiverListFlow
refreshRequests
.flatMapLatest { userRepository.receiverListFlow }
.map { receivers -> receivers.map { ReceiverListItem(it.receiverId, it.name, it.relation) } }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = emptyList(),
)

/**
* 다음 [refreshOnReturn] 이 첫 ON_RESUME(진입 자체)인지. 첫 resume 은 [recipients] 의 최초
* 구독과 같은 진입이므로 갱신하지 않는다 — VM 필드인 이유는 ReceiverHomeViewModel 의
* refreshOnReturn 과 동일, 프로세스 사망 후 복원에서도 최초 구독과 수명이 일치한다.
*/
private var isFirstResume = true

fun refresh() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[normal] flatMapLatest 가 겹침을 취소한다는 설명은 코드에서 참입니다. 다만 취소되는 것은 겹친 구독이고 서버 호출 횟수는 다릅니다.

recipients 는 stateIn(WhileSubscribed(5_000)) 이라 화면을 떠나 5초가 지나면 상류가 끊깁니다. 돌아오면 ON_START 의 재구독으로 조회가 한 번 나가고, 곧바로 ON_RESUME 의 refreshOnReturn 이 refreshRequests 를 올려 그 요청을 취소하고 두 번째 조회를 겁니다. receiverListFlow 는 콜드 플로우이고 UserRepositoryImplTest.kt:149 가 새 구독마다 서버를 다시 친다고 잠가 두었습니다.

새 테스트는 backgroundScope 로 계속 수집해서 이 구간을 재현하지 않습니다. 그리고 refresh() 를 클래스 밖에서 부르는 곳이 그 테스트뿐이라, 프로덕션 시그니처를 테스트가 정한 모양이 됩니다. refreshOnReturn 이 refreshRequests.value++ 를 직접 하면 공개할 이유가 없습니다.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

최신 HEAD f0cfec520에서도 남아 있습니다. WhileSubscribed(5_000) 구독이 중단된 뒤 복귀하면 STARTED에서 cold receiverListFlow가 다시 수집되어 getReceivers()를 호출하고, 뒤따르는 ON_RESUME에서 refreshRequests가 증가해 같은 flow를 다시 구독합니다. 이미 시작된 첫 HTTP 요청은 flatMapLatest 취소만으로 전송되지 않았다고 보장할 수 없습니다. 구독 재개와 복귀 갱신을 하나의 로드로 합치고, 수집 중단 5초 경과 → 재구독 → refreshOnReturn() 순서에서 요청이 한 번인지 테스트해 주세요. 현재 추가 테스트는 계속 수집 중인 상태만 다룹니다. 또한 refresh()는 프로덕션에서 같은 파일 내부에서만 호출되므로 private으로 좁히고 refreshOnReturn() 계약을 통해 테스트해 주세요.

refreshRequests.value++
}

/**
* 다른 화면에서 복귀했을 때의 자동 갱신 (#701). 첫 진입은 건너뛴다 — `flatMapLatest` 가
* 겹치는 구독을 알아서 취소하므로 별도의 진행 중 로드 가드는 필요 없다.
*/
fun refreshOnReturn() {
if (isFirstResume) {
isFirstResume = false
return
}
refresh()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import com.afternote.feature.timeletter.domain.model.ReceivedTimeLetter
import com.afternote.feature.timeletter.domain.repository.ReceiverTimeLetterRepository
import com.afternote.feature.timeletter.presentation.navigation.TimeLetterRoute
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand Down Expand Up @@ -37,19 +38,51 @@ class RecipientTimeLetterDetailViewModel
private val _uiState = MutableStateFlow<RecipientTimeLetterDetailUiState>(RecipientTimeLetterDetailUiState.Loading)
val uiState: StateFlow<RecipientTimeLetterDetailUiState> = _uiState.asStateFlow()

/** 진행 중인 조회 — 첫 진입 이후의 ON_RESUME 이 실행 중인 로드와 겹치면 건너뛰기 위한 가드. */
private var loadJob: Job? = null

/**
* 다음 [refreshOnReturn] 이 첫 ON_RESUME(진입 자체)인지. 첫 resume 은 init 로드와 같은
* 진입이므로 갱신하지 않는다 — VM 필드인 이유는 ReceiverHomeViewModel 의 refreshOnReturn 과
* 동일, 프로세스 사망 후 복원에서도 init 로드와 수명이 일치한다.
*/
private var isFirstResume = true

init {
load()
}

fun load() {
viewModelScope.launch {
_uiState.value = RecipientTimeLetterDetailUiState.Loading
runCatching { receiverTimeLetterRepository.getReceivedTimeLetterDetail(timeLetterReceiverId) }
.onSuccess { letter ->
_uiState.value = RecipientTimeLetterDetailUiState.Success(letter = letter)
}.onFailure {
_uiState.value = RecipientTimeLetterDetailUiState.Error
}
/**
* 다른 화면에서 복귀했을 때의 자동 갱신 (#701). 최초 진입 로드와 두 가지가 다르다 —
* 로딩을 방출하지 않고, 실패해도 보고 있던 상세를 유지한다.
* 첫 진입은 건너뛰고, 로드가 겹치면 건너뛴다.
*/
fun refreshOnReturn() {
if (isFirstResume) {
isFirstResume = false
return
}
if (loadJob?.isActive == true) return
load(showsLoading = false, keepsStateOnFailure = true)
}

fun load(
showsLoading: Boolean = true,
keepsStateOnFailure: Boolean = false,
) {
loadJob =
viewModelScope.launch {
if (showsLoading) {
_uiState.value = RecipientTimeLetterDetailUiState.Loading
}
runCatching { receiverTimeLetterRepository.getReceivedTimeLetterDetail(timeLetterReceiverId) }
.onSuccess { letter ->
_uiState.value = RecipientTimeLetterDetailUiState.Success(letter = letter)
}.onFailure {
if (!(keepsStateOnFailure && _uiState.value is RecipientTimeLetterDetailUiState.Success)) {
_uiState.value = RecipientTimeLetterDetailUiState.Error
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import androidx.lifecycle.viewModelScope
import com.afternote.feature.timeletter.domain.model.ReceivedTimeLetterList
import com.afternote.feature.timeletter.domain.repository.ReceiverTimeLetterRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand All @@ -30,19 +31,51 @@ class RecipientTimeletterViewModel
private val _uiState = MutableStateFlow<RecipientTimeletterUiState>(RecipientTimeletterUiState.Loading)
val uiState: StateFlow<RecipientTimeletterUiState> = _uiState.asStateFlow()

/** 진행 중인 조회 — 첫 진입 이후의 ON_RESUME 이 실행 중인 로드와 겹치면 건너뛰기 위한 가드. */
private var loadJob: Job? = null

/**
* 다음 [refreshOnReturn] 이 첫 ON_RESUME(진입 자체)인지. 첫 resume 은 init 로드와 같은
* 진입이므로 갱신하지 않는다 — VM 필드인 이유는 ReceiverHomeViewModel 의 refreshOnReturn 과
* 동일, 프로세스 사망 후 복원에서도 init 로드와 수명이 일치한다.
*/
private var isFirstResume = true

init {
load()
}

fun load() {
viewModelScope.launch {
_uiState.value = RecipientTimeletterUiState.Loading
runCatching { receiverTimeLetterRepository.getReceivedTimeLetters() }
.onSuccess { letters ->
_uiState.value = RecipientTimeletterUiState.Success(letters = letters)
}.onFailure {
_uiState.value = RecipientTimeletterUiState.Error
}
/**
* 다른 화면에서 복귀했을 때의 자동 갱신 (#701). 최초 진입 로드와 두 가지가 다르다 —
* 로딩을 방출하지 않고, 실패해도 보고 있던 목록을 유지한다.
* 첫 진입은 건너뛰고, 로드가 겹치면 건너뛴다.
*/
fun refreshOnReturn() {
if (isFirstResume) {
isFirstResume = false
return
}
if (loadJob?.isActive == true) return
load(showsLoading = false, keepsStateOnFailure = true)
}

fun load(
showsLoading: Boolean = true,
keepsStateOnFailure: Boolean = false,
) {
loadJob =
viewModelScope.launch {
if (showsLoading) {
_uiState.value = RecipientTimeletterUiState.Loading
}
runCatching { receiverTimeLetterRepository.getReceivedTimeLetters() }
.onSuccess { letters ->
_uiState.value = RecipientTimeletterUiState.Success(letters = letters)
}.onFailure {
if (!(keepsStateOnFailure && _uiState.value is RecipientTimeletterUiState.Success)) {
_uiState.value = RecipientTimeletterUiState.Error
}
}
}
}
}
Loading
Loading