when() and whenReady() functions allow you to wait for observables to meet specific conditions. They return promises that resolve when the condition is met, making them perfect for async workflows.
when()
Waits for a predicate to become truthy.Type Signatures
Basic Usage
With Functions
You can pass a function that returns a value:With Effect
Run an effect function when the condition is met:Multiple Conditions
Wait for multiple observables to become truthy:With Promises
Thewhen() function can also handle regular promises:
whenReady()
Waits for a value to be “ready” - not empty, null, or undefined.Type Signatures
What is “Ready”?
A value is considered ready if it’s NOT:nullundefined- Empty string (
'') - Empty array (
[]) - Empty object (
{})
Basic Usage
Waiting for Data Load
Perfect for waiting for async data to load:With Arrays
Wait for an array to have items:With Objects
Wait for an object to have properties:Multiple Ready Conditions
Combining when() and whenReady()
Use Cases
Wait for Authentication
Data Dependencies
Wait for prerequisite data before loading dependent data:Async Component Setup
Conditional Navigation
Polling Until Complete
Reactive Workflows
Comparison: when() vs whenReady()
| Feature | when() | whenReady() |
|---|---|---|
| Condition | Truthy value | Non-empty value |
| Empty array | Truthy ✓ | Not ready ✗ |
| Empty object | Truthy ✓ | Not ready ✗ |
| Empty string | Falsy ✗ | Not ready ✗ |
0 or false | Falsy ✗ | Ready ✓ |
null/undefined | Falsy ✗ | Not ready ✗ |
With Observables from Promises
Cleanup and Cancellation
The promises returned bywhen() and whenReady() automatically stop observing when they resolve:
Best Practices
- Use whenReady() for data loading: It’s specifically designed for async data
- Combine with async/await: Makes async code more readable
- Don’t forget timeout handling: Consider adding timeouts for better UX
- Use effects for transformations: The effect parameter is great for extracting values
- Array predicates for multiple conditions: Cleaner than nested promises
Timeout Pattern
Add timeouts to prevent waiting forever:Related
- Computed Observables - Reactive computed values
- linked() - Two-way computed observables
- observe() - React to changes