Is it normal always checking «isMounted» in StateNotifier when performing asynchronous calls? #644
Answered
by
rrousselGit
ViacheslavSomin
asked this question in
Q&A
-
I have data source: class WorkShiftsDataSource {
WorkShiftsDataSource(this.read, this.cancelToken);
final Reader read;
final CancelToken cancelToken;
Future<BaseResponse<List<WorkShift>>> getWorkShifts() async {
final response = await read(networkServiceProvider).request(
requestType: RequestType.get,
path: '/work-shift',
cancelToken: cancelToken,
);
return BaseResponse.fromJson(
response.data as Map<String, dynamic>,
(json) => (json as List)
.map((e) => WorkShift.fromJson(e as Map<String, dynamic>))
.toList(),
);
}
}
final workShiftsDataSourceProvider = Provider.autoDispose((ref) {
final cancelToken = CancelToken();
ref.onDispose(cancelToken.cancel);
return WorkShiftsDataSource(
ref.read,
cancelToken,
);
}); Repository: class WorkShiftsRepository {
WorkShiftsRepository(this.dataSource);
final WorkShiftsDataSource dataSource;
Future<Result<List<WorkShift>>> getWorkShifts() async {
final result = await handleResponse(
dataSource.getWorkShifts,
);
return result;
}
}
final workShiftsRepositoryProvider = Provider.autoDispose(
(ref) => WorkShiftsRepository(
ref.watch(workShiftsDataSourceProvider),
),
); And StateNotifier: class WorkShiftsNotifier extends StateNotifier<WorkShiftsState> {
WorkShiftsNotifier(this.repository) : super(const WorkShiftsState()) {
getWorkShifts();
}
final WorkShiftsRepository repository;
Future<void> getWorkShifts() async {
state = state.copyWith(
isLoading: true,
error: null,
);
final result = await repository.getWorkShifts();
if (!mounted) return;
result.when(
data: (data) {
state = state.copyWith(
workShifts: data,
);
},
error: (message) {
state = state.copyWith(
error: message,
);
},
);
state = state.copyWith(
isLoading: false,
);
}
}
final workShiftsProvider = StateNotifierProvider.autoDispose<WorkShiftsNotifier, WorkShiftsState>(
(ref) => WorkShiftsNotifier(
ref.watch(workShiftsRepositoryProvider),
),
); When To avoid BadState exception I need always to check Am I doing something wrong? |
Beta Was this translation helpful? Give feedback.
Answered by
rrousselGit
Oct 1, 2021
Replies: 1 comment 1 reply
-
This is alright. Although I would suggest using This will consume fewer resources. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
ViacheslavSomin
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is alright. Although I would suggest using
CancelToken
from dio to cancel pending network requests, instead of letting them continue and ignore their results.This will consume fewer resources.