$ Function
$ is a 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 publishing.
Type Definition
typescript
export function $<T = any>(): Stream<T | undefined>
export function $<T = any>(data: T | PromiseLike<T>): Stream<T>
export function $<T = any>(data?: T | PromiseLike<T>) {
return new Stream<T>(data)
}
Parameters
- data (optional): Initial data for the stream
- When no parameter is passed, creates an empty stream with value type T | undefined
- When data is passed, creates a stream with initial value, value type is T
Return Value
Returns a Stream instance that inherits from Observable with the following characteristics:
- Can actively push data (via next method)
- Supports immutable data updates (via set method)
- Supports chaining operations (via then method)
- Supports operators (via pipe method)
- Supports plugin system (via use method)
Use Cases
1. Creating Empty Stream
typescript
import { $ } from 'fluth'
// Create empty stream with initial value undefined
const stream$ = $()
console.log(stream$.value) // undefined
// Subscribe to data changes
stream$.then((data) => {
console.log('Received data:', data)
})
// Push data
stream$.next('hello') // Output: Received data: hello
stream$.next('world') // Output: Received data: world
2. Creating Stream with Initial Value
typescript
import { $ } from 'fluth'
// Create 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 pushing new data
stream$.next('New data') // Output: New data
3. Creating Complex Object Stream
typescript
import { $ } from 'fluth'
// Create object stream
const user$ = $({ name: 'John', age: 25, address: { city: 'Beijing' } })
// Subscribe to user info changes
user$.then((user) => {
console.log('User info:', user)
})
// Use set method for immutable updates
user$.set((user) => {
user.age = 26
user.address.city = 'Shanghai'
})
4. Creating Promise-like Stream
typescript
const customThenable = {
then: (onFulfilled: any) => {
setTimeout(() => onFulfilled('custom-thenable-value'), 50)
},
}
const stream$ = $(customThenable)
stream$.then((value) => {
console.log('custom:', value)
})