Skip to content

Instantly share code, notes, and snippets.

@newmen
Created January 22, 2019 13:15
Show Gist options
  • Save newmen/82a523dffe9c2942238faa44a1456b5a to your computer and use it in GitHub Desktop.
Save newmen/82a523dffe9c2942238faa44a1456b5a to your computer and use it in GitHub Desktop.
package com.odin.rating.application.utils;
import com.odin.rating.application.api.PersistenceHandler;
import reactor.core.publisher.Mono;
import javax.persistence.EntityTransaction;
import java.util.function.Function;
public class TransactionalMono<T> {
private final EntityTransaction transaction;
private final Mono<T> mono;
private TransactionalMono(EntityTransaction transaction, Mono<T> mono) {
this.transaction = transaction;
this.mono = mono;
}
public static <T> TransactionalMono<T> just(PersistenceHandler db, T target) {
return new TransactionalMono<>(db.beginTransaction(), Mono.just(target));
}
public <R> TransactionalMono<R> map(Function<T, R> function) {
return new TransactionalMono<>(transaction, mono.map(function));
}
public <R> TransactionalMono<R> transform(Function<TransactionalMono<T>, TransactionalMono<R>> function) {
return function.apply(this);
}
public T commit() {
PersistenceHandler.commit(transaction);
return mono.block();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment