Skip to content

Instantly share code, notes, and snippets.

@buhichan
Created September 24, 2020 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buhichan/3247c6533ac4f7b851192f54fd37fc15 to your computer and use it in GitHub Desktop.
Save buhichan/3247c6533ac4f7b851192f54fd37fc15 to your computer and use it in GitHub Desktop.
weakref service provider
window.servicemap = new Map()
class A {
constructor(){
console.log("A created")
}
}
function useService(A){
let a = servicemap.get(A)
if(!a){
const newA = new A()
servicemap.set(A, new WeakRef(newA))
return newA
}else{
return a.deref()
}
}
function wait(ms){
return new Promise(resolve=>setTimeout(resolve, ms))
}
async function someView(){
await wait(2000)
const a = useService(A)
await otherView()
return a
}
async function otherView(){
const a = useService(A)
await wait(2000)
return a
}
let time = 0
setInterval(()=>{
console.log("at "+time+++" a is, ", servicemap.get(A)?.deref() ? "not null" : "null")
},1000)
someView().then(x=>{
console.log('ended')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment