Joram Visser
10/08/2019, 7:23 AM// Example A
xService.insertX(it)
.attempt()
.unsafeRunSync()
.fold(
{ throwable: Throwable ->
request.handle(throwable)
},
{ id: UUID ->
request.createResponseBuilder(HttpStatus.CREATED)
.header(LOCATION_HEADER, "$LOCATION_HEADER_VALUE_PREFIX$id")
.build()
}
)
But a colleague pointed out that .unsafeRunSync() should never be used in production code as mentioned in the docs: “**NOTE** this function is intended for testing, it should never appear in your mainline production code!“.
Instead, I could run the IO like:
// Example B
unsafe {
runBlocking {
xService.insertX(it).attempt()
}
}.fold(
{ throwable: Throwable ->
request.handle(throwable)
},
{ id: UUID ->
request.createResponseBuilder(HttpStatus.CREATED)
.header(LOCATION_HEADER, "$LOCATION_HEADER_VALUE_PREFIX$id")
.build()
}
)
Which actually also uses .unsafeRunSync(). I’m not sure if this is safe(r) because it is inside an unsafe object?
Or I can use the unsafeRunAsync function (which doesn’t have the do not use in prod warning) in combination with nullable variable(s). (Or can/should I come up with a smarter solution?)
// Example C
var either: Either<Throwable, UUID>? = null
xService.insertX(it)
.unsafeRunAsync { result ->
either = result
}
either!!.fold(
{ throwable: Throwable ->
request.handle(throwable)
},
{ id: UUID ->
request.createResponseBuilder(HttpStatus.CREATED)
.header(LOCATION_HEADER, "$LOCATION_HEADER_VALUE_PREFIX$id")
.build()
}
)
Which actually probably needs a while (either == null) delay(Y). Which probably also needs a timeout mechanism. Which is making up for a really complex mechanism.
Or I can run the IO as a suspended function:
// Example D
runBlocking {
xService.insertX(it)
.attempt()
.suspended()
.fold(
{ throwable: Throwable ->
request.handle(throwable)
},
{ id: UUID ->
request.createResponseBuilder(HttpStatus.CREATED)
.header(LOCATION_HEADER, "$LOCATION_HEADER_VALUE_PREFIX$id")
.build()
}
)
}
This is also unsafe, but isn’t explicit about it. Which worries me even more.
I’m really not sure anymore what the best way to run an IO (in a sync way) would be.
Should I go with:
A
B
C
D
or something else, namely: ...?