HackMD
  • Prime
    Prime  Full-text search on all paid plans
    Search anywhere and reach everything in a Workspace with Prime plan.
    Got it
      • Create new note
      • Create a note from template
    • Prime  Full-text search on all paid plans
      Prime  Full-text search on all paid plans
      Search anywhere and reach everything in a Workspace with Prime plan.
      Got it
      • Sharing Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • More (Comment, Invitee)
      • Publishing
        Everyone on the web can find and read all notes of this public team.
        After the note is published, everyone on the web can find and read this note.
        See all published notes on profile page.
      • Commenting Enable
        Disabled Forbidden Owners Signed-in users Everyone
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Invitee
      • No invitee
      • Options
      • Versions and GitHub Sync
      • Transfer ownership
      • Delete this note
      • Template
      • Save as template
      • Insert from template
      • Export
      • Dropbox
      • Google Drive
      • Gist
      • Import
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
      • Download
      • Markdown
      • HTML
      • Raw HTML
    Menu Sharing Create Help
    Create Create new note Create a note from template
    Menu
    Options
    Versions and GitHub Sync Transfer ownership Delete this note
    Export
    Dropbox Google Drive Gist
    Import
    Dropbox Google Drive Gist Clipboard
    Download
    Markdown HTML Raw HTML
    Back
    Sharing
    Sharing Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    Note Permission
    Read
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Write
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    More (Comment, Invitee)
    Publishing
    Everyone on the web can find and read all notes of this public team.
    After the note is published, everyone on the web can find and read this note.
    See all published notes on profile page.
    More (Comment, Invitee)
    Commenting Enable
    Disabled Forbidden Owners Signed-in users Everyone
    Permission
    Owners
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Invitee
    No invitee
       owned this note    owned this note      
    Published Linked with GitHub
    Like1 BookmarkBookmarked
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Design Doc - @rx-angular/state author: Michael Hladky created: 2020-02-02 status: [**draft** | in review | approved | implemented | obsolete] doc url: Link to the document itself feedback url: Link to the related GitHub issue or similar design doc template version: 1.0.0 ## Objective <!-- A rough overall explanation of the idea as well as related terms and a quick scatch of the need. --> Angular is missing the glue to tie component/directive/pipe properties safely together in a reactive way. This code should solve the low level problems and leave enough space for custom wrappers. Also it can be used library independent. Furthermore it can be a starting point for a more specific state management e.g. something that couples with a specific global state lib. Fully tested, documented and usable version here: [@rx-angular/state](https://www.npmjs.com/package/@rx-angular/state) ### Approvals ### Expected User/Developer Experience <!-- Describe what will the user be able to do and how will they be able to do it thanks to this new feature. This should be done in a story format, described from the user’s/developer’s perspective, with as many details as possible but without going into the implementation details. --> With this service the developer can creat fully reactive components without using the word subscribe. It takes care of handling reactive things like the router as well as imperative like Input Bindings. Under the hood it uses some logic to take care of the following problematic things: - **NO initial state needed, state is lazy. Especially important for `*ngrxLet` as it has a lazy view** - [The reentrance situation](https://stackblitz.com/edit/rxjs-notification-reentrance) - Subscribing independent fron the view - Unsubscribing from all stateful as well as side effect subscriptions when the component is destroyed - [Ensures composition is always hot, independent of subscribers](https://stackblitz.com/edit/ng-mat-rxjs-ex-hot-vs-cold) - No need to use `subscribe` anymore. As this class only tackles low level problems it could ised as core for other architectural patterns like Alex Okrushko's [Component Store Architecture](https://hackmd.io/zLKrFIadTMS2T6zCYGyHew?view) as well as for display only components that need to be reactive. --- **The naming and number of overloads of the API can still be decided on** Setup can be done in 2 ways: Inheritance: - `class MyComponent extends RxState<{key: number}>` Injection: - `constructor(state: RxState<{key: number}>)` Interaction with the state can be done over 4 methods split into 2 styles: Imperative: - **getState** - get state imperatively - **setState** - set state imperatively Ractive: - **$** - get state reactively with no optimisations - **select** - get state reactively - **connect** - set state reactively Side effects are subscribed and unsubscribed over 1 method: - **hold** - maintain subscription for side efects ### Motivational Problems The motivation here is to provide a slim API to the user and internally handle all low-level problems. Especially helpful is the `connect` and `hold` method as they enable fully reactive and subscriptionless coding. To elaborate I solve following problems: **Selection state:** ```typescript export class MyComponent { // Full object readonly state$ = this.state.select(); // state slice readonly firstName$ = this.state.select('firstName'); // nested state slice readonly firstName$ = this.state.select('user', 'firstname'); // transformation readonly firstName$ this.state.select(map(s => s.firstName)); // transformation, behaviour readonly firstName$ = this.state.select(map(s => s.firstName), debounceTime(1000)); constructor(private state: RxState<{title: string}>) { } } ``` **Connection single value input bindings to the state:** ```typescript export class MyComponent { readonly firstName$ = this.state.select(s => s.firstName); @Input() set user(user: {firstName: string, lastName: string}) { this.state.setState(user); // with previouse state this.state.setState(s => ({...user, firstName + s.otherSlice})); } constructor(private state: RxState<{title: string}>) { } } ``` **Connection in input bindings to the state:** ```typescript export class MyComponent { readonly messages$ = this.state.select(s => s.firstName); @Input() set messages(messages$) { // with single messages - Observable<string[]> this.state.connect('messages', message$); // with single messages - Observable<string> this.state.connect(messages$, => (s, m) => ({...s, messages: s.concat([m])})); } constructor(private state: RxState<{messages: string[]}>) { } } ``` **Connection Services to the state:** ```typescript export class MyComponent { readonly userRoles$ = this.state.select(s => s.userRoles); constructor(private GlobalState: Store<{userRoles: string[], ...}>, private state: RxState<{userRoles: string[]}>) { // the full global state this.state.connect(this.globalState); // The roles selection this.state.connect('userRoles', this.globalState.select(getUserRoles())); // The roles selection, with composition of the previous state this.state.connect('userRoles', this.globalState.select(getUserRoles()), (s, userRoles) => calculation(s, userRoles)); } } ``` **Managing side effects Services to the state:** ```typescript export class MyComponent { constructor(private router: Router, private state: RxState<{messages: string[]}>) { const paramChange$ = this.router.params; // Hold an already composed side effect this.state.hold(paramChange$.pipe(tap(params => this.runSideEffect(params)))); // Hold and compose side effect this.state.hold(paramChange$, (params) => this.runSideEffect(params)); } } ``` **Mantaining loading states:** ```typescript export class MyComponent { readonly users$ = this.$.select(s => s.users); readonly loading$ = this.$.select(s => s.loading); constructor(private router: Router, private userService: UserService, private $: RxState<{user: User, loading: boolean}>) { const fetchUserOnUrlChange$ = this.router.params.pipe( switchMap(p => this.userService.getUser(p.user).pipe( map(res => ({user: res.user})), startWith({loading: true}), endWith({loading: false}) )) ); this.$.connect(userFetch$); } } ``` I also did a low level research for all cornercases we need to consider: [💾 Reactive Ephemeral State](https://dev.to/rxjs/research-on-reactive-ephemeral-state-in-component-oriented-frameworks-38lk) ### Prior Art ## Prototype ### Detailed Design <!-- Inlude some imporat cases. Error handling, and consider how to deal with e.g. performance. This section should help to understand the tricky implementations in more detail. Dont take too much attantion to typing if it bloats the code too much. --> ```typescript export class RxState<T extends object> implements Subscribable<any> { subscription = new Subscription(); effectSubject = new Subject<Observable<Partial<T>>>(); state stateObservables = new Subject<Observable<Partial<T>>>(); stateSlices = new Subject<Partial<T>>(); stateAccumulator: (st: T, sl: Partial<T>) => T = ( st: T, sl: Partial<T> ): T => { return { ...st, ...sl }; } $ = merge( this.stateObservables.pipe( this.distinctUntilChanged(), mergeAll(), observeOn(queueScheduler) ), this.stateSlices.pipe(observeOn(queueScheduler)) ).pipe( scan(this.stateAccumulator, {} as T), tap(newState => (this.state = newState)), publishReplay(1) ); constructor() {} getState(): T { return this.state; } setState<K extends keyof T>( projectState: ProjectStateFn<T> | K ): void { this.nextSlice( projectState(this.state) ); } connect<K extends keyof T>( slice$: Observable<any | Partial<T>>, projectFn: ProjectStateReducer<T, K> ): void { const project = projectOrSlices$; const slice$ = keyOrSlice$.pipe( filter(slice => slice !== undefined), map(v => project(this.getState(), v)) ); this.accumulationObservable.nextSliceObservable(slice$); } select<R>( ...opOrMapFn: OperatorFunction<T, R>[] | string[] ): Observable<T | R> { if (!opOrMapFn || opOrMapFn.length === 0) { return this.$.pipe(stateful()); } else if (isStringArrayGuard(opOrMapFn)) { return this.$.pipe(stateful(pluck(...opOrMapFn))); } else if (isOperateFnArrayGuard(opOrMapFn)) { return this.$.pipe(stateful(pipeFromArray(opOrMapFn))); } throw new WrongSelectParamsError(); } hold<S>( obsOrObsWithSideEffect: Observable<S>, sideEffectFn?: (arg: S) => void ): void { if (sideEffectFn) { this.effectSubject.next( obsOrObsWithSideEffect.pipe(tap(sideEffectFn)) ); return; } this.effectSubject.next(obsOrObsWithSideEffect); } subscribe(): Unsubscribable { const subscription = new Subscription(); subscription.add(this.$.subscribe()); subscription.add(this.effectSubject.subscribe()); return subscription; } } ``` **API usage:** - setState setState({key: value}); setState((state) => ({key: state.value + 1}) - getState getState().value; - connect connect(Observable<{key: value}>); connect(Observable<{key: value}>, (state, value) => ({key: state.value + value}) - select select(propertyKey) select((state) => state.value) - hold hold(Observable<any>) hold(Observable<someType>, (value: someType) => void) ### Caveats <!-- You may need to describe what you did not do or why simpler approaches don't work. Mention other things to watch out for (if any). Security Considerations How you’ll be secure. Considerations should include sanitization, escaping, existing security protocols and web standards, permission, user privacy, etc. None --> **New wording introduced** **New concept introduced through the connect method** - Demands good documentation - Point out anti-patterns ### Performance Considerations <!-- Try to describe under which conditions the suggested solution is performant and which factors play the key role when starting to get bad performance. Describe a specific situation in which we can run into performance problems If possible provide a POC or a theoretical explanation of a possible solution. --> **distinctUntilChanged and shareReplay are placed automatically inside the select method** **Updates from retrieved denormalized state to normalized state cause a performance impact in the state selection** **Maintaining denormalized state** - Special select logic => knowledge ## Documentation Plan <!-- Try to describe the important parts of the implementation and how to documented it e.g. importance, a priority by relevance for user, level of detail, example needed. --> Already existing docs are here as a starting point: https://github.com/BioPhoton/ngx-rx/tree/master/libs/ngx-rx-state ### Style Guide Impact <!-- Does the documentation influence the way the current style guide is structured? Also, does the new documentation introduces any technical implementations of the docs? If so please name them and give a detailed description of the impact and if possible some POCs. --> The needed documentation has no impact on the current way the documentation is maintained. ### Developer Experience Impact <!-- How will this change impact developer experience? Are we adding new tools developers need to learn? Are we asking developers to change their workflows in any way? Are we placing any new constraints on how the developer should write the code to be compatible with this change? --> This has no impact on a user's workflow but can increase performance and enables them to run zone-less. If the user decide to disable NgZone, they may need to get more familiar with RxJS operators. Other than this the user does not need to adopt or change anything. ### Breaking Changes The new pipe will not introduce any breaking changes. ## Alternatives considered <!-- Include alternate design ideas you tried out, but didn't continue with them. List their disadvantages or at least why you did not invest more time in researching them. <!-- Include alternate design ideas you tried out, but didn't continue with them. List their disadvantages or at least why you did not invest more time in researching them. **Name1** Rough description auf the case List different sub path: - A) -B) Drawbacks: - Filesize - Performance - Workflow - Tooling - Documentation - Maintainance - Breking Changes **Name2** ... --> **Why is the base class not extending from the Subject class?** It's Bad practice. **Where is the reducer?** No need for a reducer as we have no actions. **Why no actions?** We are working in a local scope, there is no need to decouple from ourselves. **How to work with entities?** Predefined methods for arrays, objects, linked lists. **Why is the selection method also reactive and not using mapper functions, e.g. createSelector only?** Because create selector is not reactive. ## Work Breakdown <!-- Explain how multiple people would actively working on the suggested code base. If needed include branching suggestions or the way code interacts --> n/a ## Resources <!-- **Research Paper/Design Docs/RFC/StackBlitz/Repositories/Video/Podcast/Blog/Tweet/Graphic:** - [Title](link.to.video/&optionalTimeInVideo=38m39s) In: Publisher, Name, Date. **Previous Versions:** // Github Release - [Github: versionNumber](https://github.com/user/repository/tree/versionNumber) // NPM Release - [NPM: versionNumber](https://www.npmjs.com/package/package-name/v/versionNumber) **Github Pull Request/Issue/Doc/Source Link** // Github Source Link - [Short Description](https://github.com/user/repository/blob/versionNumber/src/.../file.ts#optionalLineOrRange) // Github Issue - [Issue Title](https://github.com/user/repository/issues/issuesId) // Github PR - [PR Title](https://github.com/user/repository/pull/prId) --> - [💾 Reactive Ephemeral State](https://dev.to/rxjs/research-on-reactive-ephemeral-state-in-component-oriented-frameworks-38lk) In: Dev.to, Michael Hladky - [💾 NgRx Component Store](https://hackmd.io/zLKrFIadTMS2T6zCYGyHew?view) In: HackMD, Alex Okrushko - [💾 component-store-ngrx-demo](https://stackblitz.com/edit/component-store-ngrx-demo)In: StackBlitz, Alex Okrushko - [💾 NgRx Local Store](https://paper.dropbox.com/doc/NgRx-Local-Store-CskwmD7OBGca1YvMKVuPw) In: DropBox Paper, Mike Ryan

    Import from clipboard

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lost their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template is not available.


    Upgrade

    All
    • All
    • Team
    No template found.

    Create custom template


    Upgrade

    Delete template

    Do you really want to delete this template?

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Tutorials

    Book Mode Tutorial

    Slide Mode Tutorial

    YAML Metadata

    Contacts

    Facebook

    Twitter

    Feedback

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions

    Versions and GitHub Sync

    Sign in to link this note to GitHub Learn more
    This note is not linked with GitHub Learn more
     
    Add badge Pull Push GitHub Link Settings
    Upgrade now

    Version named by    

    More Less
    • Edit
    • Delete

    Note content is identical to the latest version.
    Compare with
      Choose a version
      No search result
      Version not found

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub

        Please sign in to GitHub and install the HackMD app on your GitHub repo. Learn more

         Sign in to GitHub

        HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Available push count

        Upgrade

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Upgrade

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully