Fannie  Zemlak

Fannie Zemlak

1594730940

Unlocking reactivity with Svelte and RxJS

As I keep playing around with Svelte, I keep being surprised how reactive it feels. In this article, we’ll take a quick glance at the Svelte internals to see how Svelte accomplishes this under the hood.

This is important to know, because we can use this knowledge to unlock the potentials of Svelte in combination with RxJS, without all the overhead, to end up with a truly reactive architecture. When we have a better understanding of the internals, we’ll go through some examples to take a look at the possibilities.

A Svelte component

To take a look at the internals we need a small demo application, and for this article, we have a simple counter that increments after each second.

REPL
<script>
  let tick = 0
  setInterval(() => {
    tick += 1
  }, 1000)
</script>

{ tick }

To know how Svelte compiles the above code, let’s have a look at it. In the compiled code we see that Svelte wraps the increment assignment with an [$$invalidate](https://github.com/sveltejs/svelte/blob/master/src/compiler/compile/render_dom/invalidate.ts) method. This method tells the component that the value of tick has changed, and it will flag the component as “dirty”. Because of this, the component knows has to update.

/* App.svelte generated by Svelte v3.18.2 */
import {
  SvelteComponent,
  detach,
  init,
  insert,
  noop,
  safe_not_equal,
  set_data,
  text,
} from 'svelte/internal'

function create_fragment(ctx) {
  let t

  return {
    c() {
      t = text(/*tick*/ ctx[0])
    },
    m(target, anchor) {
      insert(target, t, anchor)
    },
    p(ctx, [dirty]) {
      if (dirty & /*tick*/ 1) set_data(t, /*tick*/ ctx[0])
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) detach(t)
    },
  }
}

function instance($$self, $$props, $$invalidate) {
  let tick = 0

  setInterval(() => {
    $$invalidate(0, (tick += 1))
  }, 1000)

  return [tick]
}

class App extends SvelteComponent {
  constructor(options) {
    super()
    init(this, options, instance, create_fragment, safe_not_equal, {})
  }
}

export default App

The rest of the component’s code is mostly untouched. The code can be seen in the instance method. There’s also the create_fragment method which binds the variables to the view.

It’s possible to mimmick this update behavior by creating a reactive statement. A reactive statement will be executed when one of its dependant values has changed. You can create one by simply adding a $: prefix to the statement.

REPL
<script>
  let tick = 0
  setInterval(() => {
    tick += 1
  }, 1000)

  $: console.log(tick)
</script>

{ tick }

The compiled output of the instance wraps the console.log within the update lifecycle hook of the component.

function instance($$self, $$props, $$invalidate) {
  let tick = 0

  setInterval(() => {
    $$invalidate(0, (tick += 1))
  }, 1000)

  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*tick*/ 1) {
      $: console.log(tick)
    }
  }

  return [tick]
}

A svelte store

Now that we know how a value gets updated, we can take it a step further by creating a Svelte Store. A store holds state and is typically used to share data between multiple components.

What’s interesting for us, is that a store is subscribable. The most important piece of the contract of a store is the subscribe method. With this method, the store can let all the consumers know that its value has changed. With this, we can set up a reactive push-based architecture for our applications.

In the implementation below, a custom store is created with the initial value of 0. Inside the store, there’s an interval to increment the store’s value after each second. The store doesn’t return a value, but it returns a callback method that will be invoked when the store’s subscription is destroyed. Inside this callback method, we can put teardown logic. In our example, we use the callback method to clear the interval timer.

REPL
<script>
  import { writable } from 'svelte/store'

  let tick = writable(0, () => {
    let interval = setInterval(() => {
      tick.update(value => value + 1)
    }, 1000)

    return () => {
      clearInterval(interval)
    }
  })

  let tickValue = 0
  tick.subscribe(v => {
    tickValue = v
  })
</script>

{ tickValue }

To update the view, we create a new variable tickValue and we use the subscribe method on the store to increment tickValue when the store’s value has changed.

If we take a look at compiled output now, we see that it hasn’t changed. Just like the first example, Svelte will just wrap the assignment of tickValue with the $$invalidate method.

function instance($$self, $$props, $$invalidate) {
  let tick = writable(0, () => {
    let interval = setInterval(() => {
      tick.update(value => value + 1)
    }, 1000)

    return () => {
      clearInterval(interval)
    }
  })

  let tickValue = 0

  tick.subscribe(v => {
    $$invalidate(0, (tickValue = v))
  })

  return [tickValue]
}

Because Svelte is a compiler, it can make our lives easier. By using the $ again, and by prefixing the store variable in the HTML, we see that the store’s value will be printed out after it has changed. This is magic! It means that we don’t have to create a variable if we want to access the store’s value.

REPL
<script>
  import { writable } from 'svelte/store'

  let tick = writable(0, () => {
    let interval = setInterval(() => {
      tick.update(value => value + 1)
    }, 1000)

    return () => {
      clearInterval(interval)
    }
  })
</script>

{ $tick }

So far, we’ve seen nothing special with the compiled output of the component. But if we take a look now, we can see new internal methods, and that the code of the component instance has been modified.

/* App.svelte generated by Svelte v3.18.2 */
import {
  SvelteComponent,
  component_subscribe,
  detach,
  init,
  insert,
  noop,
  safe_not_equal,
  set_data,
  text,
} from 'svelte/internal'

import { writable } from 'svelte/store'

function create_fragment(ctx) {
  let t

  return {
    c() {
      t = text(/*$tick*/ ctx[0])
    },
    m(target, anchor) {
      insert(target, t, anchor)
    },
    p(ctx, [dirty]) {
      if (dirty & /*$tick*/ 1) set_data(t, /*$tick*/ ctx[0])
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) detach(t)
    },
  }
}

function instance($$self, $$props, $$invalidate) {
  let $tick

  let tick = writable(0, () => {
    let interval = setInterval(() => {
      tick.update(value => value + 1)
    }, 1000)

    return () => {
      clearInterval(interval)
    }
  })

  component_subscribe($$self, tick, value => $$invalidate(0, ($tick = value)))
  return [$tick, tick]
}

class App extends SvelteComponent {
  constructor(options) {
    super()
    init(this, options, instance, create_fragment, safe_not_equal, {})
  }
}

export default App

In the compiled output, we see the new component_subscribe method. To know what it does, we can take a look at the source code.

#svelte #rxjs #reactive

What is GEEK

Buddha Community

Unlocking reactivity with Svelte and RxJS
Fannie  Zemlak

Fannie Zemlak

1594730940

Unlocking reactivity with Svelte and RxJS

As I keep playing around with Svelte, I keep being surprised how reactive it feels. In this article, we’ll take a quick glance at the Svelte internals to see how Svelte accomplishes this under the hood.

This is important to know, because we can use this knowledge to unlock the potentials of Svelte in combination with RxJS, without all the overhead, to end up with a truly reactive architecture. When we have a better understanding of the internals, we’ll go through some examples to take a look at the possibilities.

A Svelte component

To take a look at the internals we need a small demo application, and for this article, we have a simple counter that increments after each second.

REPL
<script>
  let tick = 0
  setInterval(() => {
    tick += 1
  }, 1000)
</script>

{ tick }

To know how Svelte compiles the above code, let’s have a look at it. In the compiled code we see that Svelte wraps the increment assignment with an [$$invalidate](https://github.com/sveltejs/svelte/blob/master/src/compiler/compile/render_dom/invalidate.ts) method. This method tells the component that the value of tick has changed, and it will flag the component as “dirty”. Because of this, the component knows has to update.

/* App.svelte generated by Svelte v3.18.2 */
import {
  SvelteComponent,
  detach,
  init,
  insert,
  noop,
  safe_not_equal,
  set_data,
  text,
} from 'svelte/internal'

function create_fragment(ctx) {
  let t

  return {
    c() {
      t = text(/*tick*/ ctx[0])
    },
    m(target, anchor) {
      insert(target, t, anchor)
    },
    p(ctx, [dirty]) {
      if (dirty & /*tick*/ 1) set_data(t, /*tick*/ ctx[0])
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) detach(t)
    },
  }
}

function instance($$self, $$props, $$invalidate) {
  let tick = 0

  setInterval(() => {
    $$invalidate(0, (tick += 1))
  }, 1000)

  return [tick]
}

class App extends SvelteComponent {
  constructor(options) {
    super()
    init(this, options, instance, create_fragment, safe_not_equal, {})
  }
}

export default App

The rest of the component’s code is mostly untouched. The code can be seen in the instance method. There’s also the create_fragment method which binds the variables to the view.

It’s possible to mimmick this update behavior by creating a reactive statement. A reactive statement will be executed when one of its dependant values has changed. You can create one by simply adding a $: prefix to the statement.

REPL
<script>
  let tick = 0
  setInterval(() => {
    tick += 1
  }, 1000)

  $: console.log(tick)
</script>

{ tick }

The compiled output of the instance wraps the console.log within the update lifecycle hook of the component.

function instance($$self, $$props, $$invalidate) {
  let tick = 0

  setInterval(() => {
    $$invalidate(0, (tick += 1))
  }, 1000)

  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*tick*/ 1) {
      $: console.log(tick)
    }
  }

  return [tick]
}

A svelte store

Now that we know how a value gets updated, we can take it a step further by creating a Svelte Store. A store holds state and is typically used to share data between multiple components.

What’s interesting for us, is that a store is subscribable. The most important piece of the contract of a store is the subscribe method. With this method, the store can let all the consumers know that its value has changed. With this, we can set up a reactive push-based architecture for our applications.

In the implementation below, a custom store is created with the initial value of 0. Inside the store, there’s an interval to increment the store’s value after each second. The store doesn’t return a value, but it returns a callback method that will be invoked when the store’s subscription is destroyed. Inside this callback method, we can put teardown logic. In our example, we use the callback method to clear the interval timer.

REPL
<script>
  import { writable } from 'svelte/store'

  let tick = writable(0, () => {
    let interval = setInterval(() => {
      tick.update(value => value + 1)
    }, 1000)

    return () => {
      clearInterval(interval)
    }
  })

  let tickValue = 0
  tick.subscribe(v => {
    tickValue = v
  })
</script>

{ tickValue }

To update the view, we create a new variable tickValue and we use the subscribe method on the store to increment tickValue when the store’s value has changed.

If we take a look at compiled output now, we see that it hasn’t changed. Just like the first example, Svelte will just wrap the assignment of tickValue with the $$invalidate method.

function instance($$self, $$props, $$invalidate) {
  let tick = writable(0, () => {
    let interval = setInterval(() => {
      tick.update(value => value + 1)
    }, 1000)

    return () => {
      clearInterval(interval)
    }
  })

  let tickValue = 0

  tick.subscribe(v => {
    $$invalidate(0, (tickValue = v))
  })

  return [tickValue]
}

Because Svelte is a compiler, it can make our lives easier. By using the $ again, and by prefixing the store variable in the HTML, we see that the store’s value will be printed out after it has changed. This is magic! It means that we don’t have to create a variable if we want to access the store’s value.

REPL
<script>
  import { writable } from 'svelte/store'

  let tick = writable(0, () => {
    let interval = setInterval(() => {
      tick.update(value => value + 1)
    }, 1000)

    return () => {
      clearInterval(interval)
    }
  })
</script>

{ $tick }

So far, we’ve seen nothing special with the compiled output of the component. But if we take a look now, we can see new internal methods, and that the code of the component instance has been modified.

/* App.svelte generated by Svelte v3.18.2 */
import {
  SvelteComponent,
  component_subscribe,
  detach,
  init,
  insert,
  noop,
  safe_not_equal,
  set_data,
  text,
} from 'svelte/internal'

import { writable } from 'svelte/store'

function create_fragment(ctx) {
  let t

  return {
    c() {
      t = text(/*$tick*/ ctx[0])
    },
    m(target, anchor) {
      insert(target, t, anchor)
    },
    p(ctx, [dirty]) {
      if (dirty & /*$tick*/ 1) set_data(t, /*$tick*/ ctx[0])
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) detach(t)
    },
  }
}

function instance($$self, $$props, $$invalidate) {
  let $tick

  let tick = writable(0, () => {
    let interval = setInterval(() => {
      tick.update(value => value + 1)
    }, 1000)

    return () => {
      clearInterval(interval)
    }
  })

  component_subscribe($$self, tick, value => $$invalidate(0, ($tick = value)))
  return [$tick, tick]
}

class App extends SvelteComponent {
  constructor(options) {
    super()
    init(this, options, instance, create_fragment, safe_not_equal, {})
  }
}

export default App

In the compiled output, we see the new component_subscribe method. To know what it does, we can take a look at the source code.

#svelte #rxjs #reactive

Fancorico  Hunt

Fancorico Hunt

1603521914

Unlocking reactivity with Svelte and RxJS

As I keep playing around with Svelte, I keep being surprised how reactive it feels.

In this article, we’ll take a quick glance at the Svelte internals to see how Svelte accomplishes this under the hood.

This is important to know, because we can use this knowledge to unlock the potentials of Svelte in combination with RxJS, without all the overhead, to end up with a truly reactive architecture. When we have a better understanding of the internals, we’ll go through some examples to take a look at the possibilities.

A Svelte component

To take a look at the internals we need a small demo application, and for this article, we have a simple counter that increments after each second.

#svelte #rxjs

Fannie  Zemlak

Fannie Zemlak

1595901766

Building Reactive Scalable Systems

scalability word map

Building a Reactive System is all about the balance between consistency and availability and the consequences of picking one over the other. This article mainly focuses on consistency and availability and how they impact the scalability of a system.

What are Scalability, Consistency, and Availability?

A system is considered scalable if it can meet the increase in demand while remaining responsive.

A system is considered consistent if all the nodes show the same data at the same time.

A system is considered available if it remains responsive despite any failures.

How Does the Scalability of a System Differ From the Performance of the System?

Scalability and performance are related but different concepts and we need to understand what the difference is.

Scalability is the number of requests a system can handle at a time, i.e. load. It’s about optimizing the ability to handle the load, which means improving how many requests a system can handle at a time. Performance on the other hand is the time system takes to complete a single request, i.e. latency. It’s about optimizing the response time, which means improving how quickly a system can handle a single request.

Performance has a limit on reducing the response time, and we will eventually reach that limit. Whereas, scalability has no theoretical limit. We may be restricted by the implementation, but in a perfectly scalable system, we could scale forever.

So when we build Reactive Micro-services we tend to focus on improving scalability than improving performance.

How Can We Measure Scalability and Performance of a System?

Measurement like requests-per-second measures both. This makes it a valuable metric because we can use it to see whether we have improved our scalability or our performance. But it also means that it is somewhat restrictive in the sense that if it improves we can’t tell which one changed. So if we want to know where that improvement came from then we have to track scalability and performance individually.

How Can We Explain Consistency in Distributed Systems?

Distributed systems are systems that are separated by space. This means the system could be deployed across multiple data centers or within the same data center, or just deployed to different hardware or the same hardware.

Even if it’s deployed to the same hardware, a distributed system is one where information has to be transferred between different parts of that system, and when that information is transferred it’s crossing some sort of space. It could be going over a local network, or it could be writing to a disk, or it could be writing to a database.

Information cannot be transferred instantaneously, it takes some time. Granted that time could be very small but there is an amount of time that elapses during the transfer of information. Within that time duration when the transfer of the information takes place, the state of the original sender may change.

The key here is to recognize that when we are dealing with a distributed system, we are always dealing with stale data. The reality_ is eventually consistent._

What Is Eventual Consistency?

When a system stops receiving updates at least for some time, we can guarantee that all parts of the system will eventually converge on the same state. Thus in this way, we can reach that level of consistency.

Common source control tools (Git, Subversion, etc) operate on an eventually consistent model. They rely on a later merge operation to bring things back into alignment. That’s how modern source control tools achieve consistency and it’s all an eventually consistent system.

Traditional monolithic architectures are usually based around strong consistency they use a strongly consistent database like a SQL database.

What Is Strong Consistency?

When all members of a system agree on the state, before it becomes available, then we reach the level of strong consistency.

We can achieve strong consistency by introducing mechanisms like locks. Distributed system problem occurs when we have multiple things which are responsible for the same piece of data. As long as only one thing is responsible for that data, as long as we only have one instance of the lock, it’s not a distributed system problem anymore. Thus in this way, we can resolve the distributed system problem by using a non distributed resource(lock).

But when we introduce a lock, it introduces overhead in the form of contention. That overhead has consequences to our ability to be elastic, to be resilient, and it has other consequences as well.

#scalability #reactive architecture #cap theorem #reactive systems #reactive microservices #reactive

Brain  Crist

Brain Crist

1600095600

Diving Into Reactive Microservices

What are Monoliths?

To start explaining the microservices it’s useful to compare it to the monolithic application. An application is said to be a monolith when it is deployed as a single unit. Monoliths have a single shared database. They communicate with synchronous method calls where you send a message and expect a response immediately.

What are the cons of Monoliths?

  • Monoliths are limited by the maximum size of a single physical machine. As the monolith grows, it acquires more and more system resources.
  • They scale as far as the database allows because they often rely on a relational database which probably runs only a single instance in order to maintain consistency.

#reactive-systems #reactive-microservice #reactive-programming #reactive-architecture

Getting Started with Svelte Store: Reactive Context using Svelte Store

How do we make context value reactive?

Context values seemed to be stuck once initialised, how does making the changing values available through context?

#svelte #reactive