forked from deriv-com/flutter-deriv-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathavailable_contracts_bloc.dart
81 lines (68 loc) · 2.55 KB
/
available_contracts_bloc.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
80
81
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_deriv_api/api/exceptions/exceptions.dart';
import 'package:flutter_deriv_api/api/response/active_symbols_response_result.dart';
import 'package:flutter_deriv_api/api/response/contracts_for_response_result.dart';
import 'package:flutter_deriv_api/basic_api/generated/api.dart';
import '../active_symbols/active_symbols_bloc.dart';
part 'available_contracts_event.dart';
part 'available_contracts_state.dart';
/// AvailableContractsBloc
class AvailableContractsBloc
extends Bloc<AvailableContractsEvent, AvailableContractsState> {
/// Initializes
AvailableContractsBloc(ActiveSymbolsBloc activeSymbolsBloc)
: super(AvailableContractsLoading()) {
activeSymbolsBloc.stream.listen((ActiveSymbolsState activeSymbolsState) {
if (activeSymbolsState is ActiveSymbolsLoaded) {
add(
FetchAvailableContracts(
activeSymbol: activeSymbolsState.selectedSymbol,
),
);
}
});
on<FetchAvailableContracts>((FetchAvailableContracts event,
Emitter<AvailableContractsState> emit) =>
_handleFetchAvailableContracts(event, emit));
on<SelectContract>(
(SelectContract event, Emitter<AvailableContractsState> emit) =>
_handleSelectContract(event, emit));
}
Future<void> _handleFetchAvailableContracts(
FetchAvailableContracts event,
Emitter<AvailableContractsState> emit,
) async {
emit(AvailableContractsLoading());
try {
final ContractsForResponse contracts =
await _fetchAvailableContracts(event.activeSymbol);
emit(AvailableContractsLoaded(contracts: contracts.contractsFor!));
} on BaseAPIException catch (error) {
emit(AvailableContractsError(error.message));
}
}
void _handleSelectContract(
SelectContract event,
Emitter<AvailableContractsState> emit,
) {
if (state is AvailableContractsLoaded) {
final AvailableContractsLoaded loadedState =
state as AvailableContractsLoaded;
emit(AvailableContractsLoaded(
contracts: loadedState.contracts,
selectedContract: loadedState.contracts.available[event.index],
));
} else {
emit(AvailableContractsLoading());
add(FetchAvailableContracts());
}
}
Future<ContractsForResponse> _fetchAvailableContracts(
ActiveSymbolsItem? selectedSymbol,
) async =>
ContractsForResponse.fetchContractsForSymbol(ContractsForRequest(
contractsFor: selectedSymbol?.symbol,
landingCompany: '',
));
}