Guest User

View Doctor Riverpod

a guest
Oct 10th, 2023
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 2.18 KB | None | 0 0
  1.  
  2. final viewFetchedRealtimeDoctorControllerFamilyProvider = StateNotifierProvider
  3.     .family
  4.     .autoDispose<ViewDoctorController, AsyncValue<DoctorModel>, String>(
  5.         (ref, String documentId) => ViewDoctorController(
  6.             doctorModel: DoctorModel(documentId: documentId),
  7.             shouldFetchFromDb: true));
  8.  
  9. class ViewDoctorController extends StateNotifier<AsyncValue<DoctorModel>> {
  10.   final _setDoctorRepository = SetDoctorRepository();
  11.   final DoctorModel doctorModel;
  12.   final bool shouldFetchFromDb;
  13.   RealtimeSubscription? _realtimeSubscription;
  14.  
  15.   ViewDoctorController(
  16.       {required this.doctorModel, this.shouldFetchFromDb = false})
  17.       : super(const AsyncLoading()) {
  18.     _init();
  19.   }
  20.  
  21.   Future<void> _init() async {
  22.     if (shouldFetchFromDb) {
  23.       await _fetchDoctorModelFromDb();
  24.     } else {
  25.       state = AsyncData(doctorModel);
  26.     }
  27.  
  28.     await _startRealtimeSubscription();
  29.   }
  30.  
  31.   Future<void> _fetchDoctorModelFromDb() async {
  32.     final doctorModelAsync = await AsyncValue.guard(() =>
  33.         _setDoctorRepository.getDoctorModelFromDb(doctorModel.documentId));
  34.  
  35.     if (!mounted) return;
  36.  
  37.     state = doctorModelAsync;
  38.   }
  39.  
  40.   Future<void> _startRealtimeSubscription() async {
  41.     _realtimeSubscription = _setDoctorRepository
  42.         .getDoctorModelRealtimeSubscription(doctorModel.documentId);
  43.  
  44.     _realtimeSubscription?.stream.listen(_onRealtimeMessage,
  45.         onError: _onStreamError, onDone: _onStreamDone);
  46.   }
  47.  
  48.   void _onRealtimeMessage(RealtimeMessage message) {
  49.     if (message.events.contains(documentDeletedEvent)) {
  50.       state = const AsyncData(DoctorModel());
  51.     } else {
  52.       final result =
  53.           _setDoctorRepository.getDoctorModelFromRealtimeMsg(message);
  54.  
  55.       if (result != null) state = AsyncData(result);
  56.     }
  57.   }
  58.  
  59.   void _onStreamError(Object error) {
  60.     state = AsyncError(error, StackTrace.empty);
  61.   }
  62.  
  63.   void _onStreamDone() {
  64.     if (mounted) {
  65.       state = const AsyncLoading();
  66.       _init();
  67.     }
  68.   }
  69.  
  70.   Future<bool> delete() => _setDoctorRepository.deleteDoctorModel(state.value!);
  71.  
  72.   @override
  73.   void dispose() {
  74.     _realtimeSubscription?.close();
  75.     super.dispose();
  76.   }
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment