Fakultas Ilmu Komputer UI

LokasiResponseBloc.dart 2.13 KB
Newer Older
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
import 'dart:async';

import 'package:ppl_disabilitas/model/lokasi.dart';
import 'package:ppl_disabilitas/network/data/network_model.dart';
import 'package:ppl_disabilitas/repository/LokasiRepository.dart';

class LokasiResponseBloc {
  StreamController _recentSearchController;
  LokasiRepository _lokasiRepository;
  StreamController _lokasiListController;

  StreamSink<NetworkModel<LokasiListResponse>> get recentSearchSink =>
      _recentSearchController.sink;
  Stream<NetworkModel<LokasiListResponse>> get recentSearchStream =>
      _recentSearchController.stream;

  StreamSink<NetworkModel<LokasiListResponse>> get lokasiListSink =>
      _lokasiListController.sink;
  Stream<NetworkModel<LokasiListResponse>> get lokasiListStream =>
      _lokasiListController.stream;

  LokasiResponseBloc() {
    _lokasiListController =
        StreamController<NetworkModel<LokasiListResponse>>();
    _recentSearchController = StreamController<NetworkModel<LokasiListResponse>>();
    _lokasiRepository = LokasiRepository();
    fetchLokasiList();
    fetchRecentSearch();
  }

  fetchLokasiList() async {
    lokasiListSink.add(NetworkModel.loading('Getting Locations'));
    try {
      LokasiListResponse lokasiListResponse =
          await _lokasiRepository.fetchLokasi();
      print("lokasi list response: $lokasiListResponse");
      lokasiListSink.add(NetworkModel.completed(lokasiListResponse));
    } catch (e) {
      lokasiListSink.add(NetworkModel.error(e.toString()));
      print("$e");
    }
  }

  fetchRecentSearch() async {
    recentSearchSink.add(NetworkModel.loading('Getting Recent Search'));
    try {
      LokasiListResponse recentSearchData = await _lokasiRepository.fetchRecentSearch();
      print("recentSearchData ${recentSearchData.listLokasi}");
      recentSearchSink.add(NetworkModel.completed(recentSearchData));
    } catch (e) {
      recentSearchSink.add(NetworkModel.error(e.toString()));
      print("line 53 ${e.toString()}");
    }
  }

  saveRecentSearch(Lokasi search) async {
    await _lokasiRepository.saveRecentSearch(search);
  }

  dispose() {
    _recentSearchController?.close();
    _lokasiListController?.close();
  }
}