tutorial:transfer-api_storage
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
tutorial:transfer-api_storage [2021/10/30 09:58] – [What you can do with a Storage<FluidVariant>] technici4n | tutorial:transfer-api_storage [2021/10/30 10:25] (current) – external edit 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | ===== Fabric Transfer API: Understanding Storage<T> ===== | + | ===== Fabric Transfer API: Understanding Storage<FluidVariant> ===== |
//This article is part of a series on the Fabric Transfer API. [[tutorial: | //This article is part of a series on the Fabric Transfer API. [[tutorial: | ||
Line 77: | Line 77: | ||
</ | </ | ||
Hopefully you understand why this works, and why this will never duplicate or void fluid. | Hopefully you understand why this works, and why this will never duplicate or void fluid. | ||
+ | |||
+ | ==== A more complicated example: Extracting the contents of a storage ==== | ||
+ | In the previous example, we knew that we wanted to move water or lava. But what if we don't know what to extract? The answer is: iterate over the contents! | ||
+ | This example also introduces the concept of nested transactions. | ||
+ | <code java> | ||
+ | Storage< | ||
+ | Predicate< | ||
+ | long totalExtracted = 0; | ||
+ | |||
+ | // Open a transaction, | ||
+ | try (Transaction transaction = Transaction.openOuter()) { | ||
+ | // Loop over the contents! Each StorageView< | ||
+ | for (StorageView< | ||
+ | if (view.isResourceBlank()) continue; // This means that the view contains no resource, represented by FluidVariant.blank(). | ||
+ | FluidVariant storedResource = view.getResource(); | ||
+ | if (!filter.test(storedResource)) continue; // The filter rejected this resource, skip it. | ||
+ | |||
+ | // If you want to extract any amount <= view.getAmount(), | ||
+ | totalExtracted += view.extract(storedResource, | ||
+ | |||
+ | // If you want to extract either the exact amount or nothing, you can use a nested transaction! | ||
+ | try (Transaction nestedTransaction = transaction.openNested()) { | ||
+ | long amount = view.getAmount(); | ||
+ | long extracted = view.extract(storedResource, | ||
+ | if (extracted == amount) { | ||
+ | totalExtracted += amount; | ||
+ | nestedTransaction.commit(); | ||
+ | } else { | ||
+ | // If we do nothing, the extraction is cancelled immediately when nestedTransaction is closed at the end of the try { ... } block. | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | transaction.commit(); | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ==== Conclusion ==== | ||
+ | You should now be able to use '' | ||
+ | |||
+ | You should also have a look at '' | ||
+ |
tutorial/transfer-api_storage.1635587902.txt.gz · Last modified: 2021/10/30 09:58 by technici4n