hi, i have a situation where an error could happen...
# arrow
c
hi, i have a situation where an error could happen "up to once" when saving some data, due to an intermittent key constraint violation. I model this as a sealed
InternalStockAlreadyExists
error class. Here's a crude solution that enables me to retry saving one more time, but it feels wrong:
Copy code
private fun attemptSave(stockItem: InternalStockItem): Either<InternalStockAlreadyExistsError, InternalStockItem> {
    val result = stockRepository.saveStockItem(stockItem)

    val outcome = result.getOrElse {
        val secondTry = stockRepository.fetchStockByPublicReference(stockItem.publicReference)
        val secondTry = existing!!.copy(
            value = "updated value"                
        )
        stockRepository.saveStockItem(secondTry).getOrElse { null }
    }

    return outcome?.right() ?: InternalStockAlreadyExistsError.left()
}