{"id":"coffilhg/reaction","name":"reaction","scope":"coffilhg","platform":"roblox","description":"Simple lightweight reactivity core balancing memory and speed. Just Source (V), Effect (O) and Derive (C). No complicated graphs or scheduling.","version":"1.1.1","latest":"1.1.1","versions":["1.0.0","1.1.0","1.1.1"],"license":"MPL-2.0","licenseRating":"caution","licenseCaveats":["File-level copyleft: if you modify this package's own source files, those modified files must be made available under MPL-2.0. Using it unmodified in a closed-source game is fine."],"licenseVerified":true,"dependencies":{},"integrity":"0e496e43ce5cd17c5dcd5cdf451508bb6007d3c01b34653be65a8a27559ca9fe","likes":0,"downloads":0,"install":"forest install coffilhg/reaction","url":"https://forest.dev/p/roblox/coffilhg/reaction","files":"https://api.forest.dev/ai/package/roblox/coffilhg/reaction/files","readme":"# Reaction\r\nSimple lightweight reactivity core balancing memory and speed. Just Source (V), Effect (O) and Derive (C). No complicated graphs or scheduling.\r\n\r\nThe aim is to run with no dependencies and with as little implementation as possible so it can be used everywhere. This doesn't guarantee it's the best choice for every use case.\r\n\r\nSince V1.1.0 it uses the Roblox' `task` library and doesn't replace it automatically if ran with, for example **lune**. The \"everywhere\" statement above was meant as in \"everywhere inside of Roblox Studio\", like without having to root, scope, mount or do whatsoever kind of complicated sorcery around the usage.\r\n\r\n## Available Here!\r\n- **[This repository](src/init.luau) ~ [src/init.luau](src/init.luau)**\r\n- **[Wally](<https://wally.run/package/coffilhg/reaction>)**\r\n\r\n    ```toml\r\n    Reaction = \"coffilhg/reaction@1.1.1\"\r\n    ```\r\n- **[Rotriever](<https://github.com/Coffilhg/Useful-Modules/releases/tag/vReaction/1.1.1>)**\r\n\r\n    ```toml\r\n    Reaction = \"github.com/Coffilhg/Useful-Modules@Reaction/1.1.1\"\r\n    ```\r\n\r\n\r\n\r\n---\r\n\r\n## Features\r\n\r\n- Generalized Reactive core - Source, Effect and Derive\r\n- Easy to use (no root, mount or other sorcery required)\r\n- Easy to modify, it's isn't hard to read the docs (this README) and a script less than 300 lines long. (And no dependencies too)\r\n\r\n---\r\n\r\n## Basic Usage\r\n\r\n```luau\r\nconst Reaction = require(`./`)\r\nconst V, O, C, rmV, ifV, fiV = Reaction:Unpack()\r\n\r\n-- Source (Value - V)\r\nconst BalanceUSD = V(10)\r\nconst RateUSDEUR = V(0.89)\r\n-- Derive (Copy - C)\r\nconst BalanceEUR = C(function()\r\n\treturn BalanceUSD() * RateUSDEUR()\r\nend)\r\n-- Effect (Observe - O)\r\nlocal UpdateUSD: Reaction.Ou\r\nUpdateUSD = O(BalanceUSD, function(value, isDestroyed)\r\n\tif isDestroyed then\r\n\t\tUpdateUSD() -- Disconnect from Updates\r\n\t\tprint(`USD Balance unlinked; No further updates will be received.`)\r\n\t\treturn\r\n\tend\r\n\tprint(`USD Balance changed to {value}`)\r\nend)\r\nconst UpdateEUR = O(BalanceEUR, function(value, isDestroyed)\r\n\tif isDestroyed then\r\n\t\tprint(`EUR Balance unlinked; No further updates will be received.`)\r\n\t\treturn\r\n\tend\r\n\tprint(`EUR balance recomputed to {value}`)\r\nend)\r\n\r\n-- Earn 2 USD\r\nBalanceUSD(BalanceUSD()+2)\r\n-- USD Updated -> Triggers all USD observers in\r\n-- original order, including internal Observers of C\r\n-- BalanceEUR C was created before O(BalanceUSD, ...)\r\n-- So we'll first see BalanceEUR recompute which will\r\n-- trigger UpdateEUR O, then BalanceUSD O;\r\n-- Output:\r\n-- EUR balance recomputed to 10.68\r\n-- USD Balance changed to 12\r\n\r\n-- Destroy the Value\r\nrmV(BalanceUSD)\r\n-- All internal C observers will be disconnected\r\n-- All further O(BalanceUSD, ...) will be ignored and return a dummy function that does nothing\r\n-- All previously connected O' will however be able to listen to the changes\r\n-- Recommended: Disconnect all explicit O's automatically when receiving isDestroying as true\r\nprint(BalanceUSD(123))\r\n-- Output:\r\n-- ~~USD Balance changed to 123~~ -- Won't show up because of UpdateUSD() on IsDestroyed (see above)\r\n-- 123\r\n\r\n-- So now BalanceEUR will only recompute whenever\r\n-- other dependencies change, i.e. RateUSDEUR in this example\r\nRateUSDEUR(RateUSDEUR() * 1.01)\r\n-- EUR balance recomputed to 110.5647\r\n\r\n-- If we destroy all of the Values a Copy (Derived Value) relies on,\r\n-- The Copy (Derived Value) becomes a constant (though you can still use it as any usual V)\r\nrmV(RateUSDEUR)\r\n\r\nRateUSDEUR(1000) -- no effect on BalanceEUR\r\n\r\n-- Using BalanceEUR as a usual Value\r\nprint(\"BalanceEUR:\", BalanceEUR())\r\nBalanceEUR(396)\r\nprint(\"Destroying BalanceEUR\")\r\nrmV(BalanceEUR)\r\nprint(\"Remember old O's can still get updates?\")\r\nBalanceEUR(1)\r\nprint(\"So disconnect them too!\")\r\nUpdateEUR()\r\nBalanceEUR(3)\r\nprint(`Done :{BalanceEUR()}`)\r\n```\r\n\r\n---\r\n\r\n## API\r\n\r\n### **``Reaction:Unpack()``**\r\nReturns all of the API as ordered below, example usage:\r\n```luau\r\nconst V, O, C, rmV, ifV, fiV = Reaction:Unpack()\r\n```\r\n\r\n### **Value / \"*Source*\" ~ ``V<T>(val: T): V<T>``**\r\n**val** is the initial value. Returns a function, that always returns the current value of the Value.\r\n\r\n``type V<T> = (T?) -> (T)``\r\n\r\nProvide a any kind of value or **nil** as the first argument to write. Leave empty to read.\r\n\r\nThe return is typed to always be T, but in reality there's no type equality, equality and nil checks. The return is just typed as T, because it's easier to use this way.\r\n\r\nEvery change fires all observers regerdless of equality. The value can be anything. Changes to mutable values stay undetected as long as you don't re-assign them.\r\n\r\nExample usage:\r\n```luau\r\nconst Health = V(100)\r\n\r\nHealth(90) -- write -- 90\r\nprint(Health()) -- read -- 90\r\nprint(Health(50)) -- write -- 50 -- writes return the current value too!\r\n\r\nprint(Health(Health()/2)) -- writes Health to be half of the previous value and prints the result\r\n```\r\n\r\n### **Observer / \"*Effect*\" ~ ``O<T>(V: V<T>, e: E<T>): Ou``**\r\n**V** - the Value to be observed; **e** - callback firing on every change with the current value of **V** and ``true`` if it was destroyed by **rmV** (``type E<T> = (T, true?) -> ()``)\r\n\r\nReturns the function to stop observing - \"*Observer: unsee*\"; You can call it multiple times, it only takes effect the first time, then does nothing.\r\n\r\nIf the given **V** was already destroyed by **rmV**, returns a dummy function that does nothing.\r\n\r\nThe callback **e** must never error/throw. If you need a pcall, you know it. This module aims for speed, so there's no pcall internally, you won't need it in most cases anyways, and when you do, you can do it inside the callback without sacrificing the speed for ordinary derivations.\r\n\r\nYou can add / remove Observers during such **e** callback, it's safe because the Observers of a Value are first snapshotted, then fired synchronously.\r\n\r\nIf you have already started observing the **V** and it gets destroyed by **rmV**, the second argument will be ``true``. This happens only once per the lifetime of a **V**, only the first time you destroy it using **rmV**, every subsequent call of **rmV(V)** doesn not fire the Observer, beause this data was already wiped during the first use of **rmV** on the module side - the only thing preventing the observer from being garbage collected is your own connection, so it is very recommended you disconnect them, however you still have the freedom of choice.\r\n\r\ncurrent value of **V** is auto-inferred as unknown; when you try to type it, the first autocomplete option is correct\r\n\r\nExample usage:\r\n```luau\r\nconst Health = V(100)\r\n\r\nlocal HealthObserver\r\nHealthObserver = O(Health, function(currentHealth: number, isDestroyed: true?)\r\n    if isDestroyed then\r\n        print(`HP Value destroyed, disconnecting from further updates.`)\r\n        HealthObserver() -- Disconnects the observer\r\n    end\r\n    print(`HP = {currentHealth}`)\r\nend)\r\n\r\nfor i = 1, 10 do\r\n    Health(Health() - i)\r\nend\r\nrmV(Health)\r\nrmV(Health) -- Nothing happens\r\nrmV(Health) -- Nothing happens\r\nHealth(90) -- prints \"HP = 90\" only if you comment out ``HealthObserver() -- Disconnects the observer``\r\n```\r\n\r\n### **Copy \"*Derive*\" ~ ``C<T>(c: () -> (T)): V<T>``**\r\n**c** - callback that determines the derived value. This callback is called on creation (**c** is an IIFE) and on every change of an active dependency. Reconciles the active dependencies on every recompute. Tracks dependencies automatically and dynamically.\r\n\r\nThe callback must never depend on task.spawn'ed (or alike) results unless you yield them and return synchronously (e.g. you can safely use RemoteFunctions, because they yield!)\r\n\r\nThe callback **c** must never error/throw. If you need a pcall, you know it. This module aims for speed, so there's no pcall internally, you won't need it in most cases anyways, and when you do, you can do it inside the callback without sacrificing the speed for ordinary derivations.\r\n\r\n> i.e. Errors are not caught internally; use pcall inside the callback when necessary.\r\n\r\n> Manages Observers for the dependencies automatically internally, this can alter the firing order of Observers for some or all of the dependencies, this depends on the setup, read **Notes** section below.\r\n\r\nExample usage:\r\n```luau\r\nconst ValueOne = V(3)\r\nconst ValueTwo = V(11)\r\n\r\nconst ValueThree = C(function()\r\n\treturn ValueOne() * ValueTwo()\r\nend)\r\n\r\nprint(ValueThree()) -- 33\r\nValueOne(5)\r\nprint(ValueThree()) -- 55\r\n\r\n-- Technically possible, not recommended:\r\nValueThree(1) -- is not the result of the given function' return value\r\nprint(ValueThree()) -- 1\r\n```\r\n\r\n**Dependencies are resolved automatically and dynamically, so Dynamic dependency switching is supported!** e.g.:\r\n```luau\r\nlocal UseA = V(true)\r\nlocal A = V(10)\r\nlocal B = V(20)\r\n\r\nlocal Selected = C(function()\r\n    return if UseA() then A() else B()\r\nend)\r\n\r\nUseA(false) -- Selected now depends on UseA plus B, not UseA plus A\r\n```\r\n\r\n### **rmV ~ ``rmV<T>(V: V<T>)``**\r\nRemove Value (\"*``:Destroy()`` Source*\")\r\n\r\nCan be called many times on the same **V** value, only the first time makes reasonable changes, every further use only reads and wipes the internal tables regarding **V** value again.\r\n\r\n\"Destroys\" the given **V** value\r\n- Calls the cleanup, if it was a **C** kind of value\r\n- Wipes the ``Cleanups[``**V**``]`` entry\r\n- If ``Reactions[``**V**``]`` exists it contains all of the Observers for this **V**, a snapshot is taken and each Observer is notified with ``(``**V**``(), true)``\r\n- Wipes the ``Reactions[``**V**``]`` entry and then also the ``Cells[``**V**``]`` roght after\r\n\r\nAfter the given **V** value is already \"Destroyed\"\r\n- You can still use the **V** value, read and write to it.\r\n- Previously created Observers for the **V** value receive a one time notice \"isDestroyed\" (second argument) is ``true`` (it's recommended you disconnect it so it's garbage collected), afterwards you can still receive changes, but you will never receive the \"isDestroyed\" notice again.\r\n- You can still use the **V** value as a dependency for **C**, but **V**'s updates will not trigger **C** to recompute, only if **C** recomputes because of another dependency change, will it intake the newest value of **V**\r\n\r\n### **ifV ~ ``ifV<T>(V: V<T>): boolean``**\r\n\"if Value\" returns whether you can still use (add new) observers on the value. Answer the question: \"Was the value **V** never **rmV**'ed?\"\r\n\r\n### **fiV ~ ``fiV<T>(V: V<T>): boolean``**\r\n\"fi Value\" the counterpart to **ifV**. Returns whether the value was removed (\"Destroyed\") using **rmV**\r\n\r\n---\r\n\r\n## Notes\r\n\r\n- If anything. This module was designed as a Reactive core with aim for Speed, Simplicity and Versatlity. It works exactly as I designed it to, mostly for my own use, but it's fairly easy to read into it and make your own changes ~ have fun!\r\n> *\"exactly as I designed it to\"* ~ the way of how I'd expect any Reactive core to work, like I don't get the ``Vide.effect`` - isn't that almost the same as ``Vide.derive``, in my opinion an effect should react to a single source, etc. etc. personal opinions\r\n\r\n- Observer order is deterministic, however, every disconnected Observer switches places with the last (top) one to keep the speed and preserve the order. Here's an example of that:\r\n```lua\r\n-- Ordering documentation\r\n-- Example of how the deterministic order works\r\nconst N = V(0)\r\nconst A = O(N, function(v, is)\r\n    print(`A: {v}; Destroyed: {is};`)\r\nend)\r\nconst B = O(N, function(v, is)\r\n    print(`B: {v}; Destroyed: {is};`)\r\nend)\r\nconst C = O(N, function(v, is)\r\n    print(`C: {v}; Destroyed: {is};`)\r\nend)\r\nconst D = O(N, function(v, is)\r\n    print(`D: {v}; Destroyed: {is};`)\r\nend)\r\n\r\nprint(`Expect ABCD`)\r\nN(N() + 1)\r\n-- ABCD order expected\r\nA() -- Switches places with the last connected O\r\n-- The order becomes DBCA (and A is removed) so\r\n-- new order is DBC\r\nprint(`Expect DBC`)\r\nN(N() + 1)\r\n-- Current order -> switch disconnected with last -> last erased\r\nB() -- DBC -> DCB -> DC\r\nprint(`Expect DC`)\r\nN(N() + 1)\r\n\r\n-- cleanup\r\n-- btw cleaning up C, then D might be faster than D, then C\r\nC()\r\nD()\r\nprint(`Ordering learned!`)\r\n```\r\n\r\n---\r\n\r\n## Benchmarks\r\nBenchmark results can be seen **[here at Benchmarks/Results.md](Benchmarks/Results.md)**. ~~Currently they only cover **Reaction**'s own speed. Benchmarks for comparison are planned with Vision, Vide, Fluid and Seam.~~\r\n\r\nBenchmarks now cover Vide and Vision too. They were ai-generated, then human-audited and slightly edited. The initial Benchmark for Reaction was human made.\r\n\r\nLooks like it's better to only compare Reaction, Vide and Vision.\r\n\r\n---\r\n\r\n## DEPENDENCIES (if any)\r\n\r\n- None `:3`\r\n\r\n---\r\n\r\n## License & Attribution\r\n\r\nThis module is licensed under the **Mozilla Public License 2.0 (MPL-2.0)**.\r\n\r\n#### What this means for Roblox Developers:\r\n* **Use & Modify:** You can freely use this module in any public, private, or commercial Roblox game.\r\n* **File-Level Copyleft:** If you modify the source code of this module itself, you must make your modified version of the module publicly available under the MPL 2.0.\r\n* **No Viral Code Leakage:** Including this module in your game does **not** force you to open-source your other game scripts, UI layouts, or proprietary codebase. \r\n\r\nSee the full terms in the [LICENSE](LICENSE) file.\r\n\r\nAttribution to all dependencies is included in [Notice](NOTICE)\r\n\r\nCopyright © 2026 @Coffilhg (Roblox UserId 517222346)","readmeTruncated":false}