Created
July 8, 2020 17:33
-
-
Save playerx/d89d3a2295916cb048b79e4c015c2ac3 to your computer and use it in GitHub Desktop.
RXJS + defineProperty
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
import { BehaviorSubject } from "rxjs"; | |
const user$ = new BehaviorSubject<User>(null); | |
const state: State = { | |
user: null | |
}; | |
Reflect.defineProperty(state, "user", { | |
get: () => { | |
return deepFreeze(user$.value); | |
} | |
}); | |
user$.next({ id: "1", name: "ezeki", info: { test: 1 }, items: [{test2: 2}] }); | |
console.log(state.user); | |
state.user.items[0].test2 = 3; | |
// helpers | |
function deepFreeze(object) { | |
// Retrieve the property names defined on object | |
var propNames = Object.getOwnPropertyNames(object); | |
// Freeze properties before freezing self | |
for (let name of propNames) { | |
let value = object[name]; | |
if(value && typeof value === "object") { | |
deepFreeze(value); | |
} | |
} | |
return Object.freeze(object); | |
} | |
// types | |
interface State { | |
user: User | null; | |
} | |
interface User { | |
id: string; | |
name: string; | |
info: { | |
test: number; | |
}; | |
items: { | |
test2: number; | |
}[] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment