summaryrefslogtreecommitdiff
path: root/chromium/components/reading_list/core/reading_list_model.cc
blob: d3d2829a553286d76d43c36c0f2db5c54dc78d62 (plain)
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
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/reading_list/core/reading_list_model.h"

#include "base/logging.h"
#include "base/memory/ptr_util.h"

ReadingListModel::ReadingListModel() : current_batch_updates_count_(0) {}

ReadingListModel::~ReadingListModel() {
  for (auto& observer : observers_) {
    observer.ReadingListModelBeingDeleted(this);
  }
}

// Observer methods.
void ReadingListModel::AddObserver(ReadingListModelObserver* observer) {
  DCHECK(CalledOnValidThread());
  DCHECK(observer);
  observers_.AddObserver(observer);
  if (loaded()) {
    observer->ReadingListModelLoaded(this);
  }
}

void ReadingListModel::RemoveObserver(ReadingListModelObserver* observer) {
  DCHECK(CalledOnValidThread());
  observers_.RemoveObserver(observer);
}

// Batch update methods.
bool ReadingListModel::IsPerformingBatchUpdates() const {
  DCHECK(CalledOnValidThread());
  return current_batch_updates_count_ > 0;
}

std::unique_ptr<ReadingListModel::ScopedReadingListBatchUpdate>
ReadingListModel::CreateBatchToken() {
  return base::MakeUnique<ReadingListModel::ScopedReadingListBatchUpdate>(this);
}

std::unique_ptr<ReadingListModel::ScopedReadingListBatchUpdate>
ReadingListModel::BeginBatchUpdates() {
  DCHECK(CalledOnValidThread());
  auto token = CreateBatchToken();

  ++current_batch_updates_count_;
  if (current_batch_updates_count_ == 1) {
    EnteringBatchUpdates();
  }
  return token;
}

void ReadingListModel::EnteringBatchUpdates() {
  DCHECK(CalledOnValidThread());
  for (auto& observer : observers_)
    observer.ReadingListModelBeganBatchUpdates(this);
}

void ReadingListModel::EndBatchUpdates() {
  DCHECK(CalledOnValidThread());
  DCHECK(IsPerformingBatchUpdates());
  DCHECK(current_batch_updates_count_ > 0);
  --current_batch_updates_count_;
  if (current_batch_updates_count_ == 0) {
    LeavingBatchUpdates();
  }
}

void ReadingListModel::LeavingBatchUpdates() {
  DCHECK(CalledOnValidThread());
  for (auto& observer : observers_)
    observer.ReadingListModelCompletedBatchUpdates(this);
}

ReadingListModel::ScopedReadingListBatchUpdate::
    ~ScopedReadingListBatchUpdate() {
  model_->EndBatchUpdates();
}