Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DebounceObserver.java « debounce « reactivelivedata « android « niedermann « it « java « main « src « reactive-livedata - github.com/stefan-niedermann/nextcloud-deck.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4d18cfa0e5ebb3aa8685b87f770c7841cf5b11ef (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
package it.niedermann.android.reactivelivedata.debounce;

import androidx.annotation.NonNull;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.Observer;

import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class DebounceObserver<T> implements Observer<T> {
    private final MediatorLiveData<T> mediator;
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private final long timeout;
    private final ChronoUnit timeUnit;
    private T lastEmittedValue = null;
    private Instant lastEmit = Instant.now();
    private boolean firstEmit = true;
    private Future<?> scheduledRecheck;

    public DebounceObserver(@NonNull MediatorLiveData<T> mediator, long timeout, @NonNull ChronoUnit timeUnit) {
        this.mediator = mediator;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
    }

    @Override
    public void onChanged(T value) {
        final var now = Instant.now();

        if (firstEmit) {
            firstEmit = false;
            emitValue(value, now);
        } else {
            if (lastEmit.isBefore(now.minus(timeout, timeUnit))) {
                emitValue(value, now);
            } else {
                scheduleRecheck(value, getRemainingTimeToNextTimeout(now, lastEmit));
            }
        }
    }

    private void emitValue(T value, @NonNull Instant lastEmit) {
        cancelScheduledRecheck();
        mediator.postValue(value);
        this.lastEmit = lastEmit;
    }

    private Duration getRemainingTimeToNextTimeout(@NonNull Instant now, @NonNull Instant lastEmit) {
        final var millisSinceLastEmit = now.toEpochMilli() - lastEmit.toEpochMilli();
        final var millisToNextEmit = Duration.of(timeout, timeUnit).toMillis() - millisSinceLastEmit;
        return Duration.ofMillis(millisToNextEmit);
    }

    private void cancelScheduledRecheck() {
        if (scheduledRecheck != null) {
            scheduledRecheck.cancel(true);
        }
    }

    private synchronized void scheduleRecheck(T newValue, @NonNull Duration sleep) {
        cancelScheduledRecheck();
        scheduledRecheck = executor.submit(() -> {
            try {
                Thread.sleep(sleep.toMillis());
                if (!Objects.equals(lastEmittedValue, newValue)) {
                    mediator.postValue(newValue);
                    lastEmittedValue = newValue;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }
}