]> git.basschouten.com Git - openhab-addons.git/blob
c3f74aa5b61073f8b7fd7863b64361134924a6ee
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.minecraft.internal.util;
14
15 import java.util.concurrent.TimeUnit;
16
17 import rx.Observable;
18 import rx.functions.Func1;
19
20 /**
21  * RX operator subscribing to observable with a delay after it has finished.
22  *
23  * @author Mattias Markehed - Initial contribution
24  */
25 public class RetryWithDelay implements Func1<Observable<? extends Throwable>, Observable<?>> {
26
27     private final int maxRetries;
28     private final long retryDelayMillis;
29     private int retryCount;
30
31     public RetryWithDelay(final long retryDelay, TimeUnit unit) {
32         this(-1, TimeUnit.MILLISECONDS.convert(retryDelay, unit));
33     }
34
35     public RetryWithDelay(final int maxRetries, final long retryDelay, TimeUnit unit) {
36         this(maxRetries, TimeUnit.MILLISECONDS.convert(retryDelay, unit));
37     }
38
39     private RetryWithDelay(final int maxRetries, final long retryDelayMillis) {
40         this.maxRetries = maxRetries;
41         this.retryDelayMillis = retryDelayMillis;
42         this.retryCount = 0;
43     }
44
45     @Override
46     public Observable<?> call(Observable<? extends Throwable> attempts) {
47         return attempts.flatMap(new Func1<Throwable, Observable<?>>() {
48             @Override
49             public Observable<?> call(Throwable throwable) {
50                 if (maxRetries < 0 || ++retryCount < maxRetries) {
51                     return Observable.timer(retryDelayMillis, TimeUnit.MILLISECONDS);
52                 }
53
54                 return Observable.error(throwable);
55             }
56         });
57     }
58 }