$ Function
$
is the factory function for Stream
, used to create a stream. It is one of the most commonly used functions in the fluth
library, similar to Promise.resolve()
but supports continuous data emission.
Type Definition
typescript
export function $<T = any>(): Stream<T, false>
export function $<T = any>(data: T): Stream<T, true>
export function $<T = any>(data?: T) {
return new Stream<T, boolean>(data)
}
Parameters
data
(optional): Initial data for the stream- If no parameter is passed, an empty stream is created, and
value
type isT | undefined
- If data is passed, a stream with an initial value is created, and
value
type isT
- If no parameter is passed, an empty stream is created, and
Return Value
Returns a Stream
instance, which inherits from Observable
and has the following features:
- Can actively emit data (via next method)
- Supports immutable data updates (via set method)
- Supports chainable operations (via then method)
- Supports operators (via pipe method)
- Supports plugin system (via use method)
Usage Scenarios
1. Create an empty stream
typescript
import { $ } from 'fluth'
// Create an empty stream, initial value is undefined
const stream$ = $()
console.log(stream$.value) // undefined
// Subscribe to data changes
stream$.then((data) => {
console.log('Received data:', data)
})
// Emit data
stream$.next('hello') // Output: Received data: hello
stream$.next('world') // Output: Received data: world
2. Create a stream with initial value
typescript
import { $ } from 'fluth'
// Create a stream with initial value
const stream$ = $('Initial Value')
console.log(stream$.value) // "Initial Value"
// Subscribe to data changes
stream$.then((data) => {
console.log(data) // Output: Initial Value
})
// Continue to emit new data
stream$.next('New Data') // Output: New Data
3. Create a stream of complex objects
typescript
import { $ } from 'fluth'
// Create an object stream
const user$ = $({ name: 'Tom', age: 25, address: { city: 'Beijing' } })
// Subscribe to user info changes
user$.then((user) => {
console.log('User info:', user)
})
// Use set method for immutable update
user$.set((user) => {
user.age = 26
user.address.city = 'Shanghai'
})
Notes
- Type inference:
TypeScript
will automatically infer the stream type based on the data type passed in - Immutability: When using the
set
method,fluth
will automatically create immutable objects to maintain reference equality - Chainable operations: The returned stream supports chainable operations similar to
Promise
Complete Example
typescript
import { $, combine, consoleNode } from 'fluth'
// Create multiple streams
const name$ = $('Tom')
const age$ = $(25)
const city$ = $('Beijing')
// Combine streams
const user$ = combine(name$, age$, city$)
// Subscribe and process
user$.then(([name, age, city]) => {
console.log(`User: ${name}, Age: ${age}, City: ${city}`)
})
// Update data
name$.next('Jerry')
age$.next(30)
city$.next('Shanghai')
// Output: User: Jerry, Age: 30, City: Shanghai