I've had a use-case for using a `Resource<A>` with...
# arrow
p
I've had a use-case for using a
Resource<A>
with a
.use { }
that required a non-local return (and thus required
use
to be
inline
) Can anyone see any issue with taking the following approach here:
Copy code
@OptIn(DelicateCoroutinesApi::class)
suspend inline fun <A, R> Resource<A>.useInline(block: (A) -> R): R {
    val (resource, release) = allocate()
    try {
        val result = block(resource)
        release(ExitCase.Completed)
        return result
    } catch (ex: Throwable) {
        release(ExitCase.ExitCase(ex))
        throw ex
    }
}
Also, in arrow1.x we had
allocated
(deprecated) and
allocate
(the safer and recommended version) but in Arrow2,
allocate
was renamed back to
allocated
despite
allocate
feeling semantically more correct - was there any specific reason for this?
y
I don't see an issue with this directly, except perhaps cancellation handling (can't remember if the
ExitCase
function handles that).
use
should ideally be
inline
. I had a WIP PR that revamped the
ResourceScope
interface and made
use
be inline. I'll see if I can clean that up. Looking at the code,
resourceScope
should just be
inline
, not sure why it isn't.
use
should thus be inline too.
I believe
release
does the throwing automatically btw so no need to rethrow
arrow intensifies 1
p
I just checked too and saw it's fairly trivial to make
resourceScope
and
Resource<A>.use
inline for Arrow2
y
Also, a really dumb solution would be to use
merge
or
impure
as your "non-local return"
p
I still need a
throw
as the compiler doesn't know that
ExitCase.ExitCase
always returns
Cancelled | Failure
and that
release
returns
Nothing
in both cases - despite it never being reached.
y
Ooop yeah that's fair. Seems like a potential API improvement...
p
Shall I push a PR with the inline for resourceScope/use?
y
Sure, you'll have to make some things
@PublishedApi
FYI, but that should be fine!
p
https://github.com/arrow-kt/arrow/pull/3515 I've mirrored the
Resource.allocate
approach to avoid exposing the entire
ResourceScopeImpl
class in the ABI to hopefully limit any impact of future refactors