https://kotlinlang.org logo
#announcements
Title
# announcements
j

Jukka Siivonen

11/28/2019, 3:16 PM
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

marstran

11/28/2019, 3:54 PM
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

Jukka Siivonen

11/28/2019, 7:26 PM
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

marstran

11/29/2019, 10:51 AM
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

Jukka Siivonen

11/29/2019, 11:26 AM
nice 👍
2 Views