import 'dart:async';

import 'package:guru_utils/log/log.dart';
import 'package:rxdart/rxdart.dart';

import 'models/event.dart';
export 'models/event.dart';

/// Created by Haoyi on 2022/2/23

class RxEventBus {
  static RxEventBus? _instance;

  final PublishSubject<Event> _subject = PublishSubject();

  static RxEventBus _getInstance() {
    _instance ??= RxEventBus._internal();
    return _instance!;
  }

  factory RxEventBus() => _getInstance();

  static RxEventBus get instance => _getInstance();

  RxEventBus._internal();

  void post(Event event) {
    _subject.add(event);
  }

  void postDelayed(Event event, Duration duration) {
    Future.delayed(duration, () {
      post(event);
    });
  }

  StreamSubscription on(List<EventListener> listeners) {
    return _subject.asBroadcastStream().listen((event) {
      for (EventListener listener in listeners) {
        try {
          if (listener.call(event)) {
            return;
          }
        } catch (error, stacktrace) {
          Log.d("observe event error:$error $stacktrace");
        }
      }
    }, onError: (error, stacktrace) {});
  }
}
