Search code examples
javascriptreactive-programmingfrpbacon.jsevent-driven

How is reactive programming different than event-driven programming?


I am learning reactive programming and functional reactive programming in JavaScript. I am very confused.

Wikipedia says that there are various ways to write reactive code such as imperative, OORP and functional. I want to know if event-driven is just an another way to write reactive code?

How is reactive programming related to Promises? I think promises is an alternative to event-driven and callback hell.


Solution

  • How is reactive programming related to Promises? I think the promise is an alternative to event-driven and callback hell.

    In practice the two are related, I like to call Promises a gateway drug to functional reactive programming.

    +----------------------+--------+-------------+
    |                      |  Sync  |    Async    |
    +----------------------+--------+-------------+
    | Single value or null | Option | Promise     |
    | Multiple values      | List   | EventStream |
    +----------------------+--------+-------------+
    

    Promises can be thought of as EventStreams with one item, or you can think of EventStreams as multiple Promises over time.

    Promises can be chained, which is getting close to reactive programming:

    getUser() // return promise
       .then((userId) => {
           return fetch("/users/"+userId)
       })
       .then((user) => {
           alert("Fetched user: " + user.name)
       })
    

    The same with bacon.js:

    const userStream = userIdStream // EventStream of userIds
       .flatMapLatest((userId) => {
           return Bacon.fromPromise(fetch("/users/"+userId))
       })
    const userNameStream = userStream.map((user) => user.name)
    userNameStream.onValue((user) => {
       alert("Fetched user: " + user.name)
    })
    

    Both code snippets do the same thing, but there is a big difference in thinking: with promises you are thinking about handling a single action with async steps in a clear way - the thinking is imperative, you are doing things step by step. With FRP, you a saying "a stream of usernames is created from the stream of userIds by applying these two transformation steps". When you have a stream of usernames, without caring where they came from, and say "whenever there is a new username, display it to the user".

    The FRP coding style will guide you to model your problem as a stream of values (i.e. values that change over time) and the relationships between these values. If you already know Promises, the initial learning curve will be a bit easier, but the main benefit is gained only when you start thinking and modeling the problem differently - it is possible (if not very useful) to do imperative programming with FRP libraries.