-
Notifications
You must be signed in to change notification settings - Fork 136
X Managed
Managed is the functional equivalent of an imperative try-catch-finally block in Java.
Create an instance of Managed with a resource to be used, make use of the specified resource via map or flatMap and resource closing is automatically managed for you (the flow and logic is similar to that of the JDK's Optional or a Stream with a single value, except that Managed focuses is on automatic resource management).
E.g. To manage an Autocloesable resource
Try<Data,Exception> result = Managed.of(autoCloseableResource)
.map(resource->use(resource))
.map(data->save(data));
.run();
Mamaged can also automatically manage non-Autocloseable resources, the trick is to pass a Consumer that do the closing.
Managed.of(nonAutoCloseableResource,r->r.close())
.map(resource->use(resource))
.run();
In the example below we can use Managed.of to manage the Hibernate Session resource. We can use the Session to delete data from our database, and we could also use the session to create and manage a transaction. The Managed::with operator allows us to create a new artefact from the managed resource - in this case to create a Transaction from the Managed Hibernate Session, and to use it along side the managed resource (this is syntax sugar that results in much cleaner code than passing a Tuple between Managed operations).
SessionFactory factory;
Try<String, Throwable> res = Managed.of(factory::openSession)
.with(Session::beginTransaction)
.map((session, tx) ->
deleteFromMyTable(session)
.bipeek(success -> tx.commit(),error -> tx.rollback())
).foldRun(Try::flatten);
}
Managed can be leveraged from inside the cyclops IO monad, the bracket operator on IO manages the returned resource.
E.g. to read one line from a File
IO.of(this::getFile)
.bracket(file -> new BufferedReader(new FileReader(file)))
.map(reader -> reader.readLine());
.run();
The bracket method ensures the Readers are correctly closed after use.
oops - my bad