0

I’m working on an android app where users can add products to a cart, but there’s a conditional flow based on whether a delivery address is selected or not: 1. If the address is already selected, the product is added to the cart immediately. 2. If the address is not selected, the app navigates to the address selection screen. Once the user selects the address, the original action (adding the product) should be executed.

fun addProductToCart(
    scope: CoroutineScope,
    product: ProductParams,
) {
    addressJob = getCurrentDeliveryAddressUseCase()
        .onEach { deliveryAddress ->
            if (deliveryAddress == null) {
                deliveryAddressHelper.selectDeliveryAddress()
            }
        }
        .filterNotNull()
        .take(1)
        .onEach {
            addToCart(
                scope = scope,
                product = product,
            )
        }
        .launchIn(scope)
}

suspend fun selectDeliveryAddress() {
    runCatchingCancellable {
        val addresses = getDeliveryLastAddresses.invoke()
        if (addresses.isNotEmpty()) {
            navigator.goForward(
                DsDeliveryScreens.DeliveryAddressSelection(
                    addresses = addresses,
                    observerId = 1,
                )
            )
        } else {
            val deliveryArea = getDeliveryAreasUseCase.invoke()
            navigator.goForward(
                DsBaseHostScreen(
                    DsDeliveryScreens.DeliveryAddressMap(
                        deliveryAreas = deliveryArea,
                    )
                )
            )
        }
    }
}

In short, if no address is selected, we navigate to the selection screen. Once the user selected an address, getCurrentDeliveryAddressUseCase() emits the selected address, and the product is added.

This works in principle, but feels messy and has a few drawbacks. Ideally, I’d like to defer an action (like a lambda) and execute it after address selection, unfortunately, kotlin lambdas aren’t serializable, so I can’t just pass them around easily to the address selection screen (DeliveryAddressMap). I’ve considered using an event bus pattern, but that adds more complexity and still feels like a workaround.

Question: Has anyone dealt with a similar case of pending an action until a required state is set? What’s the cleanest way to handle this.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.