Skip to content

Latest commit

 

History

History
59 lines (47 loc) · 1.65 KB

when.md

File metadata and controls

59 lines (47 loc) · 1.65 KB
title sidebar_label hide_title
when
when
true

when

<script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?serve=CEBD4KQ7&placement=mobxjsorg" id="_carbonads_js"></script>
egghead.io lesson 9: custom reactions
<iframe style="border: none;" width=760 height=427 src="https://egghead.io/lessons/react-write-custom-mobx-reactions-with-when-and-autorun/embed" ></iframe>
Hosted on egghead.io

when(predicate: () => boolean, effect?: () => void, options?)

when observes & runs the given predicate until it returns true. Once that happens, the given effect is executed and the autorunner is disposed. The function returns a disposer to cancel the autorunner prematurely.

This function is really useful to dispose or cancel stuff in a reactive way. For example:

class MyResource {
    constructor() {
        when(
            // once...
            () => !this.isVisible,
            // ... then
            () => this.dispose()
        )
    }

    @computed get isVisible() {
        // indicate whether this item is visible
    }

    dispose() {
        // dispose
    }
}

when-promise

If there is no effect function provided, when will return a Promise. This combines nicely with async / await

async function() {
	await when(() => that.isVisible)
	// etc..
}