Data Streams (Watcher)

A Watcher is a use case for streaming data that continuously emits a Left Event (error) or Right Event (data) whenever our stream emits an error or new data, respectively.

The Left Event, in our case, is one of the Failure objects we previously created, whereas the Right Event is a list of Note entities on our app. Every time a new note is created, updated or deleted, our Watcher will emit a new Right Event with an updated list of the most recent notes we have.

To create a Watcher use case for streaming a list of our most recent note entries, under the note_app/modules/domain/lib/note/use_cases/ directory, create a file called watch_note_entries.dart:

import 'dart:async';

import 'package:codenic_bloc_use_case/codenic_bloc_use_case.dart';
import 'package:codenic_exception_converter/codenic_exception_converter.dart';
import 'package:domain/note/entities/note_entry.dart';
import 'package:domain/note/repositories/note_repository.dart';

/// {@template WatchNoteEntriesParams}
/// The parameters for the [WatchNoteEntries] use case.
/// {@endtemplate}
class WatchNoteEntriesParams with EquatableMixin {
  /// {@macro WatchNoteEntriesParams}
  const WatchNoteEntriesParams({required this.limit});

  /// The maximum number of [NoteEntry]s to stream.
  final int limit;

  @override
  List<Object?> get props => [limit];
}

/// {@template WatchNoteEntries}
/// See [NoteRepository.watchNoteEntries].
/// {@endtemplate}
class WatchNoteEntries
    extends Watcher<WatchNoteEntriesParams, Failure, List<NoteEntry>> {
  /// {@macro WatchNoteEntries}
  WatchNoteEntries({required this.noteRepository});

  /// A reference to the [NoteRepository] instance.
  final NoteRepository noteRepository;

  @override
  FutureOr<Either<Failure, VerboseStream<Failure, List<NoteEntry>>>> onCall(
    WatchNoteEntriesParams params,
  ) =>
      noteRepository.watchNoteEntries(limit: params.limit);
}

Last updated