#lang scheme/base
(provide
with-lazy-connect
lazy-connection
)
(define-struct lazy-connect (thunk))
(define connection
(make-parameter
(make-lazy-connect
(lambda ()
(error 'no-lazy-connection)))))
(define (with-lazy-connect connect-thunk thunk close)
(parameterize
((connection #f))
(dynamic-wind
(lambda ()
(connection
(make-lazy-connect connect-thunk)))
thunk
(lambda ()
(unless (lazy-connect? (connection))
(close (connection)))))))
(define (lazy-connection)
(let ((c (connection)))
(when (lazy-connect? c)
(connection ((lazy-connect-thunk c)))))
(connection))