cacheoff
cacheoff

Reputation: 299

How to use RXJs Subject like store variable in Svelte

How to use RXJs Subject like store variable in Svelte? You can use the Subject variable in Svelte with $ prefix. But when you bind the variable to input it throws an exception: "Error: name.set is not a function" because the Subject type has not a set method.

Upvotes: 1

Views: 517

Answers (1)

cacheoff
cacheoff

Reputation: 299

You can use RxJs Subject like a store variable in Svelte as in the example below.

<script>
    import {Subject} from "rxjs";
    
    let name = new Subject();
    setTimeout(()=>{name.next("text")}, 1000);
</script>

<h1>Hello {$name}!</h1>

But if you try to use the name variable with a bind directive it throws an exception: "Error: name.set is not a function".

<script>
    import {Subject} from "rxjs";
    
    let name = new Subject();
    $: console.log($name);  
</script>

<h1>Hello {$name}!</h1>
<input bind:value={$name} />

To solve this issue, you can add a set method to the Subject class with a simple trick :).

<script>
    import {Subject} from "rxjs";
    
    Subject.prototype.set = function (value) {
            this.next(value);
    }
    
    let name = new Subject();
    $name = "Ali";
    $: console.log($name);  
</script>

<h1>Hello {$name}!</h1>
<input bind:value={$name} />

Upvotes: 2

Related Questions