2.1.0 • Published 1 year ago

@bloc-state/bloc v2.1.0

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

@bloc-state/bloc

npm version Codecov Codecov

Introduction

@bloc-state/bloc is a state management library implementing the BLoC pattern that was first introduced by google at DartConf in 2018. This library conforms to the modern Dart Bloc library v8.x api.

Installation

npm install @bloc-state/bloc rxjs

Creating a Cubit

export class CounterCubit extends Cubit<number> {
  constructor() {
    super(0) // pass initial state to super constructor
  }

  increment() {
    this.emit((state) => state + 1)
  }

  increment() {
    this.emit((state) => state - 1)
  }
}

Using a Cubit

const counterCubit = new CounterCubit()

console.log(counterCubit.state) // 0

counterCubit.increment()

console.log(counterCubit.state) // 1

// cubit is closed and disposed, it will no longer emit new state and all observers will be unsubscribed
cubit.close()

Observing a Cubit

export class AppBlocObserver extends BlocObserver {
  override onCreate(bloc: BlocBase<any>): void {
    console.log(`onCreate: ${bloc.constructor.name}`)
  }

  override onError(bloc: BlocBase<any>, error: any): void {
    console.log(`onError: ${bloc.constructor.name}`, error)
  }

  override onChange(bloc: BlocBase<any>, change: Change<any>): void {
    console.log(`onChange: ${bloc.constructor.name}`, change)
  }

  override onClose(bloc: BlocBase<any>): void {
    console.log(`onClose: ${bloc.constructor.name}`)
  }
}
// main.tsx

// composition root of your application
Bloc.observer = AppBlocObserver()

Creating a Bloc

/// The events which `CounterBloc` will react to.
abstract class CounterEvent extends BlocEvent {}

class CounterIncrementEvent extends CounterEvent {}
class CounterDecrementEvent extends CounterEvent {}

export class CounterBloc extends Bloc<CounterEvent, number> {
  constructor() {
    super(new CounterState(0))

    this.on(CounterIncrementEvent, (event, emit) => emit((state) => state + 1))

    this.on(CounterDecrementEvent, (event, emit) => emit((state) => state - 1))
  }
}

Using a Bloc

async function main() {
  const delay = (n) => new Promise((resolve) => setTimeout(resolve, n))

  const counterBloc = new CounterBloc()

  console.log(counterBloc.state) // 0

  counterBloc.add(new CounterIncrementEvent())

  // wait for next tick in event loop
  await delay(0)

  console.log(counterBloc.state) // 1

  counterBloc.close() // close the bloc when no longer needed
}
2.1.0

1 year ago

2.0.2

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

2.0.0-beta.7

1 year ago

2.0.0-beta.6

1 year ago

2.0.0-beta.5

1 year ago

2.0.0-beta.4

2 years ago

2.0.0-beta.3

2 years ago

2.0.0-beta.2

2 years ago

2.0.0-beta.1

2 years ago

1.1.0-beta.1

2 years ago

1.0.0

2 years ago