10 ms·
Functional Reactive Programming
- vladsanchez 4y agoAs much as I'd love to learn Haskell, Lisp, OCaml or F#, try https://reactivex.io/ https://reactivex.io/ and pick your language.
- endgame 4y agoFRP is a fascinating paradigm, but I find I really have to turn my brain inside-out to "get" it. But it's really cool to have UIs that are completely consistent.
- mpweiher 4y agoThe funny thing is that good ole MVC also gave us UIs that are completely consistent.
- valenterry 4y agoNot really. It's just that at the time, SPAs and concurrent requests were not really a thing or only used rarely.
- cybrox 4y agoYou can build perfectly fine SPAs using an MVC architecture, even with lots of concurrent requests and data fetching. This is why JS has an event loop and why we invented data-binding.
- wiseowise 4y agoYou can build perfectly fine SPAs in one big file, what’s your point?
- mpweiher 4y agoYeah, actually really. Actual MVC has the model notifying the UI that it has changed and then the UI updating itself from the model, by pulling data. That's always consistent. We then did all sorts of things that we call MVC, but that do not follow the MVC-defined interaction patterns at all, particularly either the model or other views incrementally poking data into the view. That doesn't work, and it is nigh impossible to keep consistent. It also isn't MVC. I haven't written this up stand-alone, but I talk about it a little here: https://blog.metaobject.com/2022/06/blackbird-simple-reference-architecture.html https://blog.metaobject.com/2022/06/blackbird-simple-referen...
- valenterry 4y agoSo, what if you have a background process (running in the controller I assume) that updates data in the model periodically from somewhere. And at the same time you have the user making changes to the model. How is consistency guaranteed here by having "UI updating itself from the model, by pulling data"? Maybe I have a different understanding of "consistency" but this might very well lead to undesired results if the logic of data updates isn't well-controlled. The developer needs to decide if the updates can happen arbitrarily or if some kind of transaction-model needs to be used, forcing the background process to wait during user interactions or the other way around, etc. I don't see how MVC solves that problem.
- mpweiher 4y agoThis is not MVC's problem to solve. It also doesn't solve global warming. If you have unprotected multithreaded imperative updates of global data, nothing is consistent. Has nothing to do with MVC or no MVC. Actually having a consistent state to present to the UI is the model's problem. Oh, and for goodness sake, don't have any kind of async update process running in the controller. All this stuff belongs in the model. If you're doing that sort of stuff in the controller, I can see why you're having problems with concurrency. You're also almost certainly not doing MVC.
- valenterry 4y ago
- klysm 4y agoYeah but for a limited subset of desirable functionality. It sucks to use for something where you want a dynamic UI.
- mola 4y agoCan you elaborate? An example for a feature which would be a real pain in MVC but easypeasy with FRP?
- klysm 4y agoI’m not saying FRP makes anything easy, just that there’s a set of things that are desirable that MVC makes difficult. Right now I’m making a graphical node editor with a lot of drag and drop that displays live data streams. I can go into more detail about why a typical MVC sucks for this but it definitely does.
- mola 4y agoI apologize if it came out as if I don't agree. I asked out of ignorance I truly find FRP interesting and wonder when is it the right tool. It'll be very interesting to see this a sort of concrete comparison.
- daxvena 4y agoAnother funny thing is that good ole vacuum tube computers could automate computation before transistors became widespread.
- valcron1000 4y agoI disagree. The moment my controller needs to "set" or "update" something in the model the whole thing becomes a mess in my experience. FRP requires that you change the way you code but it's 100% worth IMO.
- mpweiher 4y agoWell, you can let the view do this and things get better ;-)
- ghuntley 4y agoSee also https://reflex-frp.org/ https://reflex-frp.org/
- BoumTAC 4y agoI learn FP throught ELM and I really enjoyed it. Unfortunately the language seems dead. What are the easiest FP language to learn ? I checked multiple time Haskell but it seems really hard
- smcl 4y agoF# might be a good shout.
- quickthrower2 4y agoThere is the SAFE stack https://safe-stack.github.io/docs/overview/ https://safe-stack.github.io/docs/overview/ where the E means Elmish
- airza 4y agoI have been using rxjs with typescript for some stuff. Functional reactive has proven to be a good paradigm for some stuff in the UI and thornier parts of shared state across multiple applications.
- valenterry 4y agoProper FP as in pure functional programming? Probably Purescript in the frontend (also hard) or Scala on the backend (easier, because you can also write impure code).
- cosmic_quanta 4y ago'Haskell Programming from First Principles' is a great book which helped me a lot in the beginning.
- giovannibonetti 4y agoElm started with FRP and moved on to Model-View-Update, which I agree is way simpler to understand and work with. https://elm-lang.org/news/farewell-to-frp https://elm-lang.org/news/farewell-to-frp
- macintux 4y agoVery different from Elm or Haskell, but Erlang was my gateway drug to FP. I’d tried and failed to learn Lisp on a few occasions. Elixir is more popular these days, but I still prefer Erlang’s syntax. Minimalistic, helps me “think” Erlang instead of imperative/OO.
- faleidel 4y agoAngular is using rxJs which is a reactive programming framework, but I think it was an error to do so. The angular project I am working on is now 5 years old and the parts of the application that are the least understood are the ones with more rxJs in it. We even have custom rxJs operators that nobody understand anymore... The way we do things now is to transform everything we can into promises because it's more easy to work with. With promises you have a few functions with which you can do everything. With rxJs you have dozens of function with specific use cases and most of them looks alike. It's too easy to not take the right one and new peoples in the project needs to learn a lot of things to understand the codebase. I was interviewing some angular devs aand asked the question: what is the difference between a promise and an observable and 80% of the time the answer was "for observable you need to sunscribe to get the result"). That shows a clear lack of understand of rxJs. Anybody had a better experience with angular and rxJs?
- dhucerbin 4y agoYes and no. We found that rx.js is bad for coordination. I think coordination is a big part of services in angular UI's. You need to fetch some data, wait for it, ask for different thing, maybe change some state. Promises and await are great for this and especially await syntax is readable (go channels could be even better). In rx.js you had to nest multiple switchMaps for dependant queries and for state - you either produce state as a stream result or you put some `tap` or `subscribe` with `takeUntil`. But rx.js shines with more complex user interactions - drag and drops, brushes, interactive forms (angular has nice, reactive form api). We even put some state machines inside streams, so input signals produced events. and we had `scan` operator that manipulated machine. My personal issue with rx.js is that BehaviourSubject is leaky - you can do anything to it, and break it's property of 'always has a value'. It is nice if your service is a reactive value that you can inject and transform or render using async pipe. But you need to be careful what operators are you using on it.
- WorldMaker 4y ago> My personal issue with rx.js is that BehaviourSubject is leaky RxJS best practice is that BehaviorSubject should be used infrequently to never, mostly as "internal plumbing" to things like building your own mini-Operators, and that they should never escape an API boundary. If you need to pass a BehaviorSubject to a consumer you always .asObservable() it and the consumer must treat it like a regular Observable (your API boundary is always Observable<T>, never Subject<T>). (BehaviorSubjects are an imperative "back door" that breaks building things the reactive way.) That's one of my biggest personal problems with the Angular core libraries is how many BehaviorSubjects leak out everywhere in that API design. EventEmitter is a big giant BehaviorSubject. The Routing APIs leak BehaviorSubjects. Angular's "Reactive" Forms leak imperative BehaviorSubjects all over the place. The bad use of BehaviorSubjects by the core libraries leaks to the rest of the Anuglar ecosystem and there are so many "Angular best practices" that are "RxJS worst practices" purely from these early API design decisions. > We found that rx.js is bad for coordination. RxJS is great at "coordination". It requires a different mindset. Angular is awful at helping you get into that mindset. Angular's HttpClient is especially "bad, heavy promises masquerading as Observables" which makes it hard to think of queries/API fetches as events that can return refreshed data over time (streams of fetch results), more similar to those user interactions you saw good results from. There's a lot of useful coordination operators in RxJS beyond `switchMap()` like `mergeAll()` and `concatAll()`. If you think of a stream of request events flowing into a stream of response events flowing into a state machine (possibly with a very simple, similar `scan` to your user interaction model to reduce your state over time, a little like the "redux" pattern [1]), RxJS can be brilliant for "coordination" as data arrives. (Angular kind of sets it up to fail. With how HttpClient works. With how Async Pipe works and isn't the default.) > or you put some `tap` or `subscribe` with `takeUntil` This is also where Angular "best practices" and I diverge, and I think also stems from RxJS "worst practices". RxJS best practice is also to use `tap` as infrequently as possible. It's a worst chance escape hatch at best. RxJS best practice is also the `subscribe` as "late" as possible and also as infrequently as possible and that you never have a `subscribe` without an `unsubscribe` to clean up resources, including memory. (Which can be very important if you are trying to do everything the reactive way. You can move all your setup into Observables, including the setup and teardown of vanilla JS components.) The overuse of `subscribe` in Angular components seems one of the biggest obvious reasons why so much of the usage of Observables in the Angular ecosystem looks like bloated Promises. (Which is directly a bad example set by the core library's own HttpClient.) (I also think some of Angular "best practices" uses of `takeUntil` aren't great either. I was taught that Observable completion should "mean something" as it's a key event in the stream, and shutting down Observables early mean you miss later events.) If Angular's template language took Observables directly, without needing an "async pipe", most of those manual subscribes would just vanish in an instant. Most of the needs for `ngOnInit` and `ngOnDestroy` "lifecycle events" disappear. (As Observables have lifecycle events already in subscribe/unsubscribe setup/teardown.) Angular could have not needed Zone.js at all nor its complex "Change Detector" apparatus. Angular could have done smart things in coordinating Observable observations by templates. (A lot of what React's last several major releases have been about in building its Concurrency, Suspense, and related systems out have been about among other things throttling "non-important" DOM updates together to things like requestAnimationFrame and doing very complicated work under the hood to set all that up from VDOM changes. In an Observable world you can pipe a `mergeAll()` through `debounce(0, requestAnimationFrameScheduler)` and get things like that "really easy".) I wound up trying to encode all of my personal best practices for writing powerful, reactive components in Angular into an opinionated reusable "component framework": https://www.npmjs.com/package/angular-pharkas https://www.npmjs.com/package/angular-pharkas I haven't yet found a good way to encode my mindset to "reactive service classes" in Angular, in part because "it feels obvious" to me and isn't really a pattern so much as a mindset, which I know it is exactly not obvious or lots of people would be doing it and Angular's ecosystem would be less full of bad examples. Probably a key place to start based on the above conversation is that I almost always wrap any calls to Angular's HttpClient in a "forever Observable". Whatever the input is to call that HTTP API, whether it is a refresh signal or some sort of other input event (Observable) hide the `switchMap()` in an Observable of results over time. Most "dependent" data streams are coordinated sometimes as simply as a `combineLatest()` and others are `scan()` reductions (even full "state machines" in some cases of those reducers). Everything is returned as Observable<T> and never any Subject<T>. Everything flows into the Components and `subscribes` are as late as possible (and these days hidden entirely away in "Pharkas" binds). Learn when to `share()` observables (or more often `shareReplay(x)`) and reuse existing Observables rather than build new ones. I don't know how much that helps. I've been able to wring a lot of good reactive programming out of a massive Angular frontend, but I've been fighting Angular itself (and the terrible debugging/performance experience of the gross, unnecessary Zone.js), and the greater ecosystem of "Angular best practices" the whole way. Every Junior Developer with Angular experience that looks at the code for the first time generally thinks it is readable but that "it looks nothing like Angular I am used to". It's definitely not "Angular best practices" as people are learning them today. Also, a useful related tip for removing most uses of `tap`: install `rxjs-spy`. It's great. It provides a very simple `tag('some-observable-name`)` operator that is a no-op in Production builds and in Development builds gives you a `window.spy` toolkit that lets you log events from tagged Observables (or a regex matching tagged Observable names) or even set debugger breakpoints at tags. [1] Though I tend towards "lots of little observable streams" over combined ball of single state refiltered back into little observables like in the "proper" "redux" pattern or how tools like NgRx try to implement that in the Angular world.
- InflexHQ 4y agoI'll be adding this to Inflex (https://inflex.io/ https://inflex.io/), I have the design worked out on paper. (But I'll be open sourcing it first and releasing as a desktop app, and then get back to dev.) It's also helpful to think of FRP in terms of "push" and "pull" (for which there's a related paper by the same chap). This refers to control flow. Behaviours are "pull" i.e. your program has to pull from them. Events are "push" i.e. your program gets pushed to, by some other active agent. The trick is how one "makes things happen". If you want to pull the latest tweets every 5 seconds, in reverse order, you might have code that looks like: timer(5).joinWith(latestTweets).map(reverse) Similar to promises you're always building up more declarative values. It's just that FRP has a clean semantic description. There are laws, and no assumptions about time/imperative escape hatches. It can be quite hard to use it practically for some types of apps; space leaks and cycles are a challenge, and some code can be messy. Research continues. But for my simpler use-case, it's a very good fit. Spreadsheets use "volatile" cells to side-step the whole issue of interacting with time and the outside world, but it leaves a bad taste in the mouth because it's a hack that makes state implicit. FRP brings a strong mental framework to address this properly, rather than as an afterthought.
- shinzui 4y agoI got the impression that you're already using FRP for inflex.
- InflexHQ 4y agoThe UI is implemented using Halogen, a front end library for PureScript. That handles redisplay when recalculation happens. That’s more like React or Elm. Rather, I mean exposing an FRP API to people using the Inflex language.
- bbkane 4y agoInflex looks really great! I love the no-grid + reactivity premise!
- InflexHQ 4y ago
- cybrox 4y agoAs someone who had to maintain two applications written entirely using the FRP Paradigm (Rx in Kotlin/Swift with a heavy focus on FRP principles), I am fascinated the idea but I absolutely hated the experience. Writing behaviour flows can end in beautiful blocks of easy to understand operations. However, as these get more complex and you need to combine multiple data streams, logic is scattered all over a module. Refactoring data-flows that go through multiple modules is a huge hassle. Sometimes, we would spend hours just refactoring data-passing, wrapping and unwrapping and tests surrounding modules, because we needed to pass some additional values. It doesn't help that you have to set up all behaviours at setup time, which means the code is mixed with one-time setup code which regularly confused people working on the projects as to what is run at startup time and what is run per-event. Debugging itself was mostly hampered by the libraries that we used not providing adequate tools for the job but even if they did, it was a lot more difficult to reason about compared to something like async/await based code or callback chains. I can imagine FRP works better in purely functional languages but implementing FRP paradigms in general purpose languages - especially when interfacing with non-functional code, which is often necessary - has led to nothing but trouble for me.
- zionic 4y agoI moved everything from RxSwift to Combine back with iOS (13?) and was happy with the experience. As for the “complexity”, I largely solved this problem by limiting dimensionality of stream handling to 1, and chaining streams via explicit function calls so that I was never map/flat mapping stream to stream to stream etc. This made everything much easier to understand in my projects, and also test etc. But you’re right as now that async/await is in Swift proper I’m not sure it makes much sense anymore. There’s still some functionality I need that seems external (looks like async sequence might help once I can use iOS16 as a min spec?). Beyond the basic stuff, it’s essential that I can: 1) Define explicit timeouts that throw typed errors for every step of the async process 2) Have the ability to queue up an array of async operations (each with their own timeouts), dispatch them in a serial queue, then buffer their results to emit a single array, itself with a global timeout 3) While doing all of the above, I need a way to terminate async actions “in flight” upon receipt of some signal, so that a long running async queue can be aborted if necessary Once all of the above is possible I’ll probably go back and rip out Rx (Combine) in a few years for a pure async-await implementation, but that will take forever
- revskill 4y agoFRP is simply the true way to build real time application.
- marcosdumay 4y agoYou mean interactive? I don't see how FRP helps with real time.
- dllthomas 4y agoI expect the parent means having some portions of the output change without user input, which isn't either of those if we're being picky.
- marcosdumay 4y agoHum, I'll complain about calling it "being picky". We are up to 3 completely different theories about what the GP meant, and no way to tell them apart.
- dllthomas 4y ago"Discerning"? :)
- marcosdumay 4y agoAnyway, I think you are correct, and I don't know any good name for software that reacts to the wall time.
- dllthomas 4y agoIn the context of games it is in fact "real time", at least in "real time strategy" (and as opposed to "turn based") but obviously that conflicts with the engineering definition. Maybe "live"?
- kgr 4y agoThis short fun video demonstrates how FRP is related/similar to spreadsheets: https://www.youtube.com/watch?v=-fbq-_H6Lf4 https://www.youtube.com/watch?v=-fbq-_H6Lf4
- aporetics 4y agoFor those of you interested in hearing the inventor of FRP talk about it, take a look at Conal Elliott’s retrospective talk in 2015: https://youtu.be/j3Q32brCUAI https://youtu.be/j3Q32brCUAI Especially useful for those whose only exposure to FRP is through frp-inspired libraries (they’re not the same thing).
- 725686 4y agoThis might be interesting from a CS perspective, but useless to developers who have to create real life messy business applications.
- aporetics 4y agoAs a developer of real life messy code (as opposed to unreal life?), I have never found ignoring CS to be beneficial; and on the other hand, deciding in advance that CS is not helpful is hubristic: you never know when theoretical insight will become actionable. On the other hand, who wouldn’t be curious? Like someone who purports to enjoy fast cars but has no interest in understanding internal combustion or electric engines?
- dfee 4y agoIs it viable to build a traditional web product/company on top of Haskell? That sounds like a silly question - but I’m serious. I’m enamored by the beauty of FP, but I’m not sure if there’s enough tooling or libraries to get to market. For example - GraphQL. There are two packages (mu and morpheus), but neither clearly document their feature parity in relation to other packages for other languages - and things like dataloaders. The Reddit almost encourages people to use a different language, too.
- hiptobecubic 4y agoI have never tried, but my impression is basically "You could, but why would you?" Haskell had a big jump in popularity around a decade ago, but it didn't gain traction with the "i'll grind 17 hours a day to become a rockstar ninja whatever" demographic that every language seems to bootstrap itself off of. I won't speculate as to why, but the end result is that Haskell is missing a lot of "adapter"-style libraries and instead is just a bunch of building blocks. Yeah you can write great stuff in Haskell, but also you have no choice. No one else has written what you need so you'll be writing it yourself. The benefits of Haskell don't even _really_ seem that useful when you're just writing yet another big ass crud app where the main goal is to convert json into some other json and then maybe render it. I could see it making more sense in specific domains where the main challenge is wrangling a complex mess of business logic into something you can be confident about. Not like "is my shopping cart correct" but "how can I optimize this PCB design to reduce trace length and total area?"
- yakshaving_jgt 4y ago> The benefits of Haskell don't even _really_ seem that useful when you're just writing yet another big ass crud app where the main goal is to convert json into some other json and then maybe render it. The benefits have been massive for me, and I'm often doing basically this. Maybe you should just try it?
- Iceland_jack 4y agoYou would be surprised how much Haskell is practical for boring stuff, try it out http://learnyouahaskell.com/ http://learnyouahaskell.com/
- dllthomas 4y agoThere's a lot of talk of Rx libs, but from https://reactivex.io/intro.html https://reactivex.io/intro.html I see: "It is sometimes called “functional reactive programming” but this is a misnomer. ReactiveX may be functional, and it may be reactive, but “functional reactive programming” is a different animal. One main point of difference is that functional reactive programming operates on values that change continuously over time, while ReactiveX operates on discrete values that are emitted over time." At the same time, I see lots of references to FRP on https://reactivex.io/tutorials.html https://reactivex.io/tutorials.html so I am not sure what the actual position of the project is, or the actual status of the technologies (maybe things have changed?).
- Paradigma11 4y agoThere was reactive programming coming from c#. You can look up Eric Meijer and the duality of Observable and IEnumerable. It is discrete, push and event based and has some history with flow based programming. FRP comes from Conal Elliot and has a continuous pull based aspect with maybe an additional reactive event based component on the side. Then the javascript horde discovered rx and since functional programming is cool, rp is now frp.
- dllthomas 4y agoBut an article on FRP on haskell.org is probably actually about FRP, right?
- Paradigma11 4y agoIndeed. That is why you have: at : Behavior α → Time → α which is a pull based continuous data type. This is a very elegant concept but comes with its own set of difficulties if implemented naively (space and time leaks). A similar concept is shown here: https://www.microsoft.com/en-us/research/uploads/prod/2000/09/pj-eber.pdf https://www.microsoft.com/en-us/research/uploads/prod/2000/0... Imo the main problem in the end is/was that not many problems are that conveniently described as continuous. Discrete and push based (rx) can do most things and even that is overused. It makes problems that are otherwise very hard, much easier to describe and solve using the many powerful combinators https://www.learnrxjs.io/learn-rxjs/operators https://www.learnrxjs.io/learn-rxjs/operators On the other hand you make all those easy problems quite a bit harder and if you are not disciplined you end up with complex rx "queries" that have semantics that you dont understand.