https://kotlinlang.org logo
Title
c

chanjungskim

04/11/2023, 5:28 AM
how can I make callback suspend?
fun updateCartUi(response: Result<CartInfo>, onSuccess: suspend (CartInfo) -> Unit, onFailure: suspend (Throwable) -> Unit) { ... }
Can I use something like this?
a

alex.krupa

04/11/2023, 6:15 AM
Is your goal to suspend until
updateCartUi
finishes?
c

chanjungskim

04/11/2023, 7:33 AM
No, until, onSuccess and onFailure. it will have some functions that need coroutine block. here's my full code:
class 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.
I found a bug that
updateCartUi
is not called until
shopRepository.fetchCartInfo()
gets the response... How can I solve this issue or is there any better solution?
Hmmm. Is there any way to update only last call response...?