Skip to content

Instantly share code, notes, and snippets.

@shirakaba
Last active April 28, 2021 16:40
Show Gist options
  • Save shirakaba/67bba7c277666e991d91d15b0a2894c9 to your computer and use it in GitHub Desktop.
Save shirakaba/67bba7c277666e991d91d15b0a2894c9 to your computer and use it in GitHub Desktop.
Svelte store contract for one API of a class
<script>
import { writable } from 'svelte/store';
class TransactionManager {
constructor(){
this.transactionCount = -1;
this.transactionQueue = [];
this._transactionIsInFlight = writable(false);
}
startTransaction(){
const id = ++this.transactionCount;
this.transactionQueue.push(id);
console.log(`startTransaction(); Queue: ${JSON.stringify(this.transactionQueue)}`);
this._updateTransactionInFlight();
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._updateTransactionInFlight();
}
_updateTransactionInFlight() {
this._transactionIsInFlight.set(this.transactionQueue.length > 0);
}
transactionIsInFlight(){
return this._transactionIsInFlight;
}
}
const transactionManager = new TransactionManager();
let transactionIsInFlight = transactionManager.transactionIsInFlight();
$: {
// My aim is to make this be re-evaluated each time transactionManager.stopTransaction() is called.
console.log("transactionIsInFlight status evaluated:", $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>{$transactionIsInFlight}</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment