Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- final viewFetchedRealtimeDoctorControllerFamilyProvider = StateNotifierProvider
- .family
- .autoDispose<ViewDoctorController, AsyncValue<DoctorModel>, String>(
- (ref, String documentId) => ViewDoctorController(
- doctorModel: DoctorModel(documentId: documentId),
- shouldFetchFromDb: true));
- class ViewDoctorController extends StateNotifier<AsyncValue<DoctorModel>> {
- final _setDoctorRepository = SetDoctorRepository();
- final DoctorModel doctorModel;
- final bool shouldFetchFromDb;
- RealtimeSubscription? _realtimeSubscription;
- ViewDoctorController(
- {required this.doctorModel, this.shouldFetchFromDb = false})
- : super(const AsyncLoading()) {
- _init();
- }
- Future<void> _init() async {
- if (shouldFetchFromDb) {
- await _fetchDoctorModelFromDb();
- } else {
- state = AsyncData(doctorModel);
- }
- await _startRealtimeSubscription();
- }
- Future<void> _fetchDoctorModelFromDb() async {
- final doctorModelAsync = await AsyncValue.guard(() =>
- _setDoctorRepository.getDoctorModelFromDb(doctorModel.documentId));
- if (!mounted) return;
- state = doctorModelAsync;
- }
- Future<void> _startRealtimeSubscription() async {
- _realtimeSubscription = _setDoctorRepository
- .getDoctorModelRealtimeSubscription(doctorModel.documentId);
- _realtimeSubscription?.stream.listen(_onRealtimeMessage,
- onError: _onStreamError, onDone: _onStreamDone);
- }
- void _onRealtimeMessage(RealtimeMessage message) {
- if (message.events.contains(documentDeletedEvent)) {
- state = const AsyncData(DoctorModel());
- } else {
- final result =
- _setDoctorRepository.getDoctorModelFromRealtimeMsg(message);
- if (result != null) state = AsyncData(result);
- }
- }
- void _onStreamError(Object error) {
- state = AsyncError(error, StackTrace.empty);
- }
- void _onStreamDone() {
- if (mounted) {
- state = const AsyncLoading();
- _init();
- }
- }
- Future<bool> delete() => _setDoctorRepository.deleteDoctorModel(state.value!);
- @override
- void dispose() {
- _realtimeSubscription?.close();
- super.dispose();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment