io.vlingo.lattice.model.CompletionTranslator Maven / Gradle / Ivy
Show all versions of vlingo-lattice Show documentation
// Copyright © 2012-2020 VLINGO LABS. All rights reserved.
//
// This Source Code Form is subject to the terms of the
// Mozilla Public License, v. 2.0. If a copy of the MPL
// was not distributed with this file, You can obtain
// one at https://mozilla.org/MPL/2.0/.
package io.vlingo.lattice.model;
import java.util.function.Function;
import io.vlingo.actors.CompletesEventually;
/**
* Supports providing a latent {@code Completes} outcome by way of {@code CompletesEventually}.
* Used by {@code StateObjectQueryActor} to provide answers from queries that complete asynchronously
* to the original message delivery.
* @param the outcome value type of the internal {@code Function}.
* @param the return value type of the internal {@code Function}.
*/
public class CompletionTranslator {
private final CompletesEventually completes;
private final Function translator;
/**
* Answer a new instance of {@code CompletionSupplier} if the {@code supplier} is not {@code null};
* otherwise answer null.
* @param translator the {@code Function} of the eventual outcome, or null if none is provided
* @param completes the CompletesEventually through which the eventual outcome is sent
* @param the outcome value type of the internal {@code Function}.
* @param the return value type of the internal {@code Function}.
* @return {@code CompletionBiSupplier}
*/
public static CompletionTranslator translatorOrNull(final Function translator, final CompletesEventually completes) {
if (translator == null) {
return null;
}
return new CompletionTranslator(translator, completes);
}
/**
* Completes the outcome by executing the {@code Function} translator to produce the answer.
* @param outcome the O outcome to be translated into a completion value
*/
public void complete(final O outcome) {
completes.with(translator.apply(outcome));
}
/**
* Construct my default state.
* @param translator the {@code Function} to translate the eventual outcome with which to complete
* @param completes the {@code CompletesEventually} used to complete the eventual outcome
*/
private CompletionTranslator(final Function translator, final CompletesEventually completes) {
this.translator = translator;
this.completes = completes;
}
}