View Javadoc
1   /**
2    * This file Copyright (c) 2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.ui.framework;
35  
36  
37  import java.io.Serializable;
38  import java.util.Objects;
39  import java.util.Optional;
40  
41  import org.slf4j.Logger;
42  import org.slf4j.LoggerFactory;
43  
44  import io.reactivex.BackpressureStrategy;
45  import io.reactivex.disposables.Disposable;
46  import io.reactivex.functions.Consumer;
47  import io.reactivex.subjects.BehaviorSubject;
48  import io.reactivex.subjects.Subject;
49  
50  /**
51   * Observable property. Provides two flavours of observation:
52   * <ul>
53   * <li>null-safe, which yields optionals to the observers</li>
54   * <li>nullable, which may broadcast nulls</li>
55   * </ul>
56   * <p>
57   * Also provides the mutation capabilities in imperative and functional styles. Imperative is
58   * useful when we merely want to swap one value with another, whereas the functional one can be
59   * used when e.g. another element needs to be added to a collection.
60   * </p>
61   * @param <T> item type.
62   */
63  public interface ContextProperty<T> extends Serializable {
64  
65      Logger log = LoggerFactory.getLogger(ContextProperty.class);
66  
67      Disposable observeNullable(Consumer<T> action);
68  
69      Disposable observe(Consumer<Optional<T>> action);
70  
71      Optional<T> value();
72  
73      void set(T value);
74  
75      void mutate(Consumer<T> mutator);
76  
77      default T nullableValue() {
78          //TODO: Not get if that's nullable!
79          return value().get();
80      }
81  
82      /**
83       * A wrapper around {@link ContextProperty}.
84       * @param <T> item type.
85       */
86      class Wrapper<T> implements ContextProperty<T> {
87  
88          private final ContextProperty<T> delegate;
89  
90          public Wrapper(ContextProperty<T> delegate) {
91              this.delegate = delegate;
92          }
93  
94          @Override
95          public Disposable observeNullable(Consumer<T> action) {
96              return this.delegate.observeNullable(action);
97          }
98  
99          @Override
100         public Disposable observe(Consumer<Optional<T>> action) {
101             return this.delegate.observe(action);
102         }
103 
104         @Override
105         public Optional<T> value() {
106             return this.delegate.value();
107         }
108 
109         @Override
110         public void set(T value) {
111             this.delegate.set(value);
112         }
113 
114         @Override
115         public void mutate(Consumer<T> mutator) {
116             this.delegate.mutate(mutator);
117         }
118     }
119 
120     //    Flowable<Optional<T>> observe();
121 
122     /**
123      * Default implementation of {@link ContextProperty}.
124      *
125      * @param <T>
126      *     property value type
127      */
128     class Impl<T> implements ContextProperty<T> {
129 
130         private static final Logger log = LoggerFactory.getLogger(Impl.class);
131 
132         private T lastValue = null;
133 
134         private Subject<Optional<T>> subject = BehaviorSubject.createDefault(Optional.empty());
135 
136         Impl() {
137             subject.onNext(Optional.empty());
138         }
139 
140         public Disposable observeNullable(Consumer<T> action) {
141             return subject
142                     .toFlowable(BackpressureStrategy.LATEST)
143                     .map(optional -> optional)
144                     .subscribe(
145                             optional -> action.accept(optional.orElse(null)),
146                             e -> log.error("Failed to dispatch context property change: {}", e.getMessage(), e));
147         }
148 
149         @Override
150         public Disposable observe(Consumer<Optional<T>> action) {
151             return subject.subscribe(action, e -> log.error("Failed to dispatch context property change: {}", e.getMessage(), e));
152         }
153 
154         @Override
155         public void mutate(Consumer<T> mutator) {
156             value().ifPresent(value -> {
157                 try {
158                     mutator.accept(value);
159                 } catch (Exception e) {
160                     log.error("{}", e.getMessage(), e);
161                 }
162                 doSet(value, true);
163             });
164         }
165 
166         @Override
167         public Optional<T> value() {
168             return Optional.ofNullable(this.lastValue);
169         }
170 
171         @Override
172         public void set(T value) {
173             doSet(value, false);
174         }
175 
176         private void doSet(T value, boolean shouldNotifyOnSameItem) {
177             if (!shouldNotifyOnSameItem && Objects.equals(value, this.lastValue)) {
178                 return;
179             }
180 
181             this.lastValue = value;
182             this.subject.onNext(Optional.ofNullable(value));
183         }
184 
185 //        @Override
186 //        public Flowable<Optional<T>> observe() {
187 //            return subject.toFlowable(BackpressureStrategy.LATEST);
188 //        }
189     }
190 }