Created
September 24, 2020 03:33
-
-
Save buhichan/3247c6533ac4f7b851192f54fd37fc15 to your computer and use it in GitHub Desktop.
weakref service provider
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
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