chanjungskim
04/11/2023, 5:28 AMfun updateCartUi(response: Result<CartInfo>, onSuccess: suspend (CartInfo) -> Unit, onFailure: suspend (Throwable) -> Unit) { ... }
Can I use something like this?alex.krupa
04/11/2023, 6:15 AMupdateCartUi
finishes?chanjungskim
04/11/2023, 7:33 AMclass UiUpdateManager @Inject constructor(
) {
private var remainCallNumbers = 0
suspend fun updateCartUi(
response: Result<CartInfo>,
onSuccess: suspend (CartInfo) -> Unit,
onFailure: suspend (Throwable) -> Unit
) {
remainCallNumbers++
response.onSuccess {
remainCallNumbers--
if(remainCallNumbers == 0) {
onSuccess.invoke(it)
}
}.onFailure {
remainCallNumbers--
onFailure.invoke(it)
}
}
}
My goal is to update the UI at the last response when it's successful.
And I use it on ViewModel
val uiUpdateManager = UiUpdateManager()
fun fetchCartInfo() = viewModelScope.launch{
uiUpdateManager.updateCartUi(
response = shopRepository.fetchCartInfo(),
onSuccess = { ... },
onFailure = { ... }
)
}
fun add...
fun remove...
fun etc...
I have like 8 APIs. in one Screen and the response is late. So, I'd like to update the UI first and update the UI again with the last response only because the return type is the same and it updates the UI before all request finished. For example, I call, add -> add -> remove -> add then, the UI will be add -> add -> remove -> add -> (2 items now, but response now comes) -> one item -> two item -> one item -> two item
I expect it to be add -> add -> remove -> add -> (2 items now, but response now comes) -> skip update -> skip update -> skip update -> two item.
Then, the UI will display the synced data.updateCartUi
is not called until shopRepository.fetchCartInfo()
gets the response... How can I solve this issue or is there any better solution?