Is there more cleaner way to achive something like...
# announcements
j
Is there more cleaner way to achive something like this (template = Spring transaction template)
Copy code
transactionTemplate.execute {
            val bar = doSomethingTransactional()
            if (bar) {
                { doSomethingOutsideTransaction(bar) }
            } else {
                { doSomethingElseOutsideTransaction() }
            }
        }?.invoke()
So that part of the code is run inside transaction and some part of code is run outside transaction (with data found inside transaction). Example is simplified a lot from real use case so bear with me.. :)
Copy code
fun <T> TransactionTemplate.executeWithCallback(action: () -> () -> T): T? {
        return this.execute { action.invoke() }?.invoke()
    }
this would guide to return a function and would invoke it if available
m
I see that
execute
returns the result of the callback. Can't you just do this?
Copy code
val bar = transactionTemplate.execute {
  doSomethingTransactional()
}

if (bar) {
  doSomethingOutsideTransaction(bar)
} else {
  doSomethingElseOutsideTransaction()
}
j
yes but the problem is that non-transactional functions take mixed number of different parameters that then should be all returned from execute, but my simplified example does not show this
so it's more like
Copy code
transactionTemplate.execute {
            val bar = doSomethingTransactional()
            if (bar) {
                { doSomethingOutsideTransaction(bar) }
            } else {
                val foo = ...
                val baz = ...
                { doSomethingElseOutsideTransaction(foo, baz) }
            }
        }?.invoke()
m
Then I would use a sealed class I think. For example:
Copy code
sealed class BarResult
data class WithBar(bar: Bar) : BarResult
data class WithoutBar(foo: Foo, baz: Baz): BarResult

val res = transactionTemplate.execute {
  val bar = doSomethingTransactional()
  if (bar) WithBar(bar)
  else WithoutBar(foo, baz)
}

when(res) {
 is WithBar -> doSomethingOutsideTransaction(res.bar)
 is WithoutBar -> doSomethingElseOutsideTransaction(res.foo, res.baz)
}
j
nice 👍