Fakultas Ilmu Komputer UI

KomentarBloc.dart 2.46 KB
Newer Older
1
2
3
4
5
6
7
8
9
import 'dart:async';

import 'package:ppl_disabilitas/model/komentar.dart';
import 'package:ppl_disabilitas/network/data/network_model.dart';
import 'package:ppl_disabilitas/repository/KomentarRepository.dart';

class KomentarBloc {
  KomentarRepository _komentarRepository;
  StreamController _komentarListController;
10
  List<KomentarModel> allKomentarFromApi;
11
12
13
14
15
16

  StreamSink<NetworkModel<KomentarList>> get komentarListSink =>
      _komentarListController.sink;
  Stream<NetworkModel<KomentarList>> get komentarListStream =>
      _komentarListController.stream;

17
  KomentarBloc(String namaLokasi) {
18
19
    _komentarListController = StreamController<NetworkModel<KomentarList>>();
    _komentarRepository = KomentarRepository();
20
    fetchKomentarList(namaLokasi);
21
22
  }

23
  fetchKomentarList(String namaLokasi) async {
24
25
26
    komentarListSink.add(NetworkModel.loading('Getting Komentar'));
    try {
      KomentarList komentarListResponse =
27
          await _komentarRepository.fetchKomentar(namaLokasi);
28
      allKomentarFromApi = List.from(komentarListResponse.allKomentar);
Fakhira Devina's avatar
Fakhira Devina committed
29

30
31
32
33
34
35
36
      komentarListSink.add(NetworkModel.completed(komentarListResponse));
    } catch (e) {
      komentarListSink.add(NetworkModel.error(e.toString()));
      print("$e");
    }
  }

37
38
39
40
41
42
43
44
45
46
47
48
49
  filterKomentarList(String tag, bool value, List<KomentarModel> currentList) {
    if (value) {
      for (var komentar in allKomentarFromApi) {
        if (komentar.tag.contains(tag)) {
          currentList.add(komentar);
        }
      }
    } else {
      currentList.removeWhere((komentar) => komentar.tag.contains(tag));
    }
    komentarListSink.add(NetworkModel.completed(KomentarList(currentList)));
  }

50
51
  sortKomentarList(int option, List<KomentarModel> currentList) {
    if (option == 0) {
52
      currentList.sort((next_komentar, prev_komentar) =>
53
          prev_komentar.date_time.compareTo(next_komentar.date_time));
54
    } else if (option == 1) {
55
      currentList.sort((next_komentar, prev_komentar) =>
56
57
          (prev_komentar.like + prev_komentar.dislike)
              .compareTo(next_komentar.like + next_komentar.dislike));
58
59
60
    } else if (option == 2) {
      currentList.sort((next_komentar, prev_komentar) =>
          prev_komentar.like.compareTo(next_komentar.like));
61
    }
62
63
64
65
66
67
    komentarListSink.add(NetworkModel.completed(KomentarList(currentList)));
  }

  resetKomentarList() {
    komentarListSink
        .add(NetworkModel.completed(KomentarList(allKomentarFromApi)));
68
69
  }

70
71
72
73
  dispose() {
    _komentarListController?.close();
  }
}