Last active
April 28, 2021 16:40
-
-
Save shirakaba/e3259f8031dc777744052edb1b38cf13 to your computer and use it in GitHub Desktop.
Svelte store contract for all APIs of a class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <script> | |
| import { writable } from "svelte/store"; | |
| class TransactionManager { | |
| constructor(){ | |
| this.transactionCount = -1; | |
| this.transactionQueue = []; | |
| this._transactionIsInFlight = writable(this); | |
| } | |
| startTransaction(){ | |
| const id = ++this.transactionCount; | |
| this.transactionQueue.push(id); | |
| console.log(`startTransaction(); Queue: ${JSON.stringify(this.transactionQueue)}`); | |
| this._transactionIsInFlight.set(this); | |
| return id; | |
| } | |
| stopTransaction(id){ | |
| const indexOfTransaction = this.transactionQueue.findIndex(t => t === id); | |
| if(indexOfTransaction !== -1){ | |
| this.transactionQueue.splice(indexOfTransaction, 1); | |
| } | |
| console.log(`endTransaction(${id}); Queue: ${JSON.stringify(this.transactionQueue)}`); | |
| this._transactionIsInFlight.set(this); | |
| } | |
| subscribe(subscriber) { | |
| return this._transactionIsInFlight.subscribe(subscriber); | |
| } | |
| transactionIsInFlight(){ | |
| return this.transactionQueue.length > 0; | |
| } | |
| } | |
| const transactionManager = new TransactionManager(); | |
| $: { | |
| // My aim is for this to be re-evaluated each time transactionManager.stopTransaction() is called. | |
| console.log("transactionIsInFlight status evaluated:", $transactionManager.transactionIsInFlight()); | |
| } | |
| let retryTimeout; | |
| function retry(){ | |
| const transactionId = transactionManager.startTransaction(); | |
| retryTimeout = setTimeout(() => { | |
| transactionManager.stopTransaction(transactionId); | |
| retryTimeout = setTimeout(() => retry(), 1000); | |
| }, 1000); | |
| } | |
| retry(); | |
| </script> | |
| <!-- My aim is for this to flip between true and false every second as transactions start and stop. --> | |
| <p>{$transactionManager.transactionIsInFlight()}</p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment