felangel / bloc

A predictable state management library that helps implement the BLoC design pattern
https://bloclibrary.dev
MIT License
11.8k stars 3.39k forks source link

Adding duration to bloc_concurrency. #3003

Closed fauzanpahlawan closed 2 years ago

fauzanpahlawan commented 2 years ago
on<FetchEvent>(
  (event, emitter) async {
    await Future.delayed(const Duration(milliseconds: 500));
    await _onFetched(event, emitter);
  },
  transformer: restartable(),
);

Is there a better way to add duration to bloc_concurrency? I'm using restartable() to debounce event added through onChanged from a TextField, so it will only handle the last event added (when the user stop typing).

Thank you.

marcossevilla commented 2 years ago

hey @fauzanpahlawan! You can create a custom debounce EventTransformer like this:

EventTransformer<Event> debounce<Event>(Duration duration) {
  return (events, mapper) => events.debounce(duration).switchMap(mapper);
}

And then use it as you were using restartable.

Closing for now but feel free to continue the conversation. 👍

Aerofluxx commented 1 year ago

I hope this one will not reopen on comment, if so, sorry guys.

Just in case that somebody is looking for this in the actual version of dart / flutter / bloc

import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:rxdart/transformers.dart';

EventTransformer<Event> debounce<Event>(Duration duration) {
  return (Stream<Event> events, Stream<Event> Function(Event) mapper) => events
      .transform(
        StreamTransformer<Event, Event>.fromHandlers(
          handleData: (Event event, EventSink<Event> sink) => sink.add(event),
          handleDone: (EventSink<Event> sink) => sink.close(),
          handleError: (Object error, StackTrace stackTrace, EventSink<Event> sink) => sink.addError(error, stackTrace),
        ),
      )
      .debounceTime(duration)
      .switchMap(mapper);
}

Thanks for your post @marcossevilla 👍