-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathbase_view_model.dart
79 lines (64 loc) · 2.03 KB
/
base_view_model.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import 'dart:async';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_template/foundation/extensions/object_ext.dart';
import 'package:flutter_template/presentation/entity/effect/effect.dart';
import 'package:flutter_template/presentation/entity/screen/screen.dart';
import 'package:flutter_template/presentation/entity/screen/screen_state.dart';
import 'package:rxdart/rxdart.dart';
abstract class BaseViewModel<SCREEN extends Screen,
SCREEN_STATE extends ScreenState> extends StateNotifier<SCREEN_STATE> {
final List<StreamSubscription> _streamSubscriptions =
List.empty(growable: true);
SCREEN? _screen;
final _effectController = StreamController<Effect?>();
Stream<Effect?> get effectStream => _effectController.stream;
@protected
onInit();
@protected
onBind(SCREEN? screen) {}
BaseViewModel(super.state) {
logD("onInit.");
onInit();
}
SCREEN? get screen => _screen;
bind(SCREEN? screenData) {
_screen = screenData;
logD("onBind.");
onBind(screen);
}
setState(SCREEN_STATE Function(SCREEN_STATE state) reducer) {
final newState = reducer(state);
if (!const DeepCollectionEquality().equals(state, newState)) {
state = newState;
}
}
setEffect(Effect effect) {
_effectController.add(effect);
_effectController.add(null);
}
listen<T>({
required Stream<T> stream,
required void Function(T data) onData,
}) {
final subscription = stream.listen(onData);
_streamSubscriptions.add(subscription);
}
listenDebounce<T>({
required Stream<T> stream,
required Duration debounceDuration,
required void Function(T data) onData,
}) {
final subscription = stream.debounceTime(debounceDuration).listen(onData);
_streamSubscriptions.add(subscription);
}
@override
void dispose() {
super.dispose();
logD("onDispose.");
for (var subscription in _streamSubscriptions) {
subscription.cancel();
}
}
}