|
| 1 | +import 'dart:async'; |
| 2 | + |
| 3 | +import 'package:flutter/foundation.dart'; |
| 4 | + |
| 5 | +/// A mixin that provides a stream of update events. |
| 6 | +/// |
| 7 | +/// This mixin is used to notify listeners when an update occurs. |
| 8 | +/// It is used in the [RefreshStreamMixin] class. |
| 9 | +/// |
| 10 | +/// Example: |
| 11 | +/// ```dart |
| 12 | +/// class MyRepository with RefreshNotifierMixin { |
| 13 | +/// void create() { |
| 14 | +/// // Execute create logic |
| 15 | +/// refreshListeners(RefreshType.create); |
| 16 | +/// } |
| 17 | +/// |
| 18 | +/// void update() { |
| 19 | +/// // Execute update logic |
| 20 | +/// refreshListeners(RefreshType.update); |
| 21 | +/// } |
| 22 | +/// } |
| 23 | +/// ``` |
| 24 | +/// |
| 25 | +/// Then you can listen to the refresh stream like this: |
| 26 | +/// ```dart |
| 27 | +/// myRepository.listen((event) { |
| 28 | +/// switch (event) { |
| 29 | +/// case RefreshType.create: |
| 30 | +/// // Execute create logic |
| 31 | +/// break; |
| 32 | +/// case RefreshType.update: |
| 33 | +/// // Execute update logic |
| 34 | +/// break; |
| 35 | +/// } |
| 36 | +/// }); |
| 37 | +/// ``` |
| 38 | +mixin RefreshStreamMixin { |
| 39 | + final _refreshStream = StreamController<RefreshType>.broadcast(); |
| 40 | + |
| 41 | + /// Adds a new refresh event to the stream. |
| 42 | + @protected |
| 43 | + void refreshListeners(RefreshType event) => _refreshStream.add(event); |
| 44 | + |
| 45 | + /// Listener function for the refresh stream. |
| 46 | + StreamSubscription<RefreshType> listen(void Function(RefreshType event) events) { |
| 47 | + return _refreshStream.stream.listen(events); |
| 48 | + } |
| 49 | + |
| 50 | + /// Closes the refresh stream. |
| 51 | + Future<void> close() async { |
| 52 | + await _refreshStream.close(); |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +/// The type of refresh event. |
| 57 | +enum RefreshType { |
| 58 | + /// The [RefreshType.create] event should be used when a new object is created. |
| 59 | + create, |
| 60 | + |
| 61 | + /// The [RefreshType.update] event should be used when an object is updated. |
| 62 | + update, |
| 63 | + |
| 64 | + /// The [RefreshType.delete] event should be used when an object is deleted. |
| 65 | + delete, |
| 66 | + |
| 67 | + /// The [RefreshType.custom] event should be used when a custom event occurs, |
| 68 | + /// if the refresh should trigger different logic than a normal create/update/delete event. |
| 69 | + /// This way you can separate behaviour in the place where you are listening to the events |
| 70 | + custom, |
| 71 | +} |
0 commit comments