aboutsummaryrefslogtreecommitdiff
path: root/core
diff options
context:
space:
mode:
Diffstat (limited to 'core')
-rw-r--r--core/README.md35
-rw-r--r--core/src/main/kotlin/ca/allanwang/kau/kotlin/Debouncer.kt124
-rw-r--r--core/src/main/kotlin/ca/allanwang/kau/kotlin/LazyResettable.kt2
-rw-r--r--core/src/main/kotlin/ca/allanwang/kau/logging/TimberLogger.kt3
-rw-r--r--core/src/test/kotlin/ca/allanwang/kau/kotlin/DebounceTest.kt53
5 files changed, 202 insertions, 15 deletions
diff --git a/core/README.md b/core/README.md
index 2c8ae9d..6796082 100644
--- a/core/README.md
+++ b/core/README.md
@@ -5,19 +5,19 @@
## Contents
* [KPrefs](#kprefs)
-* [Changelog XML](#changelog)
+* [Changelog XML](#changelog-xml)
* [FAQ XML](#faq-xml)
* [Kotterknife](#kotterknife)
* [Ripple Canvas](#ripple-canvas)
* [MeasureSpecDelegate](#measure-spec-delegate)
* [CollapsibleViewDelegate](#collapsible-view-delegate)
* [Swipe](#swipe)
+* [Debounce](#debounce)
* [Timber Logger](#timber-logger)
* [Email Builder](#email-builder)
-* [Extensions](#extensions)
+* [Extension Functions](#extension-functions)
* [Lazy Resettable](#lazy-resettable)
-<a name="kprefs"></a>
## KPrefs
A typical SharedPreference contains items that look like so:
@@ -71,7 +71,6 @@ object MyPrefs : KPref() {
Notice that it is a `val` and takes no default. It will return true the first time and false for all subsequent calls.
-<a name="changelog"></a>
## Changelog XML
Create an xml resource with the following structure:
@@ -109,7 +108,6 @@ Here is a template xml changelog file:
</resources>
```
-<a name="faq-xml"></a>
## FAQ XML
There is another parser for a FAQ list with the following format:
@@ -123,7 +121,6 @@ Call `kauParseFaq` and pass a callback taking in a `List<Pair<Spanned, Spanned>`
By default, the questions are numbered, and the content is formatted with HTML.
You may still need to add your own methods to allow interaction with certain elements such as links.
-<a name="kotterknife"></a>
## Kotterknife
KAU comes shipped with [Kotterknife](https://github.com/JakeWharton/kotterknife) by Jake Wharton.
@@ -134,7 +131,6 @@ These variants are weakly held in the private `KotterknifeRegistry` object, and
values through the `Kotterknife.reset` method. This is typically useful for Fragments, as they do not follow
the same lifecycle as Activities and Views.
-<a name="ripple-canvas"></a>
## Ripple Canvas
Ripple canvas provides a way to create simultaneous ripples against a background color.
@@ -145,21 +141,18 @@ They can be used as transitions, or as a toolbar background to replicate the loo
Many ripples can be stacked on top of each other to run at the same time from different locations.
The canvas also supports color fading and direct color setting so it can effectively replace any background.
-<a name="measure-spec-delegate"></a>
## Measure Spec Delegate
If you ever have a view needing exact aspect ratios with its parent and/or itself, this delegate is here to help.
Implementing this in any view class unlocks its attributes, giving you three layers of view measuring to ensure exact sizing.
More information can be found in the [klass file](https://github.com/AllanWang/KAU/blob/master/core/src/main/kotlin/ca/allanwang/kau/ui/views/MeasureSpecDelegate.kt)
-<a name="collapsible-view-delegate"></a>
## Collapsible View Delegate
A common animation is having a view that can smoothly enter and exit by changing its height.
This delegate will implement everything for you and give you the methods `expand`, `collapse`, etc.
See the [kclass file](https://github.com/AllanWang/KAU/blob/master/core/src/main/kotlin/ca/allanwang/kau/ui/views/CollapsibleViewDelegate.kt) for more details.
-<a name="swipe"></a>
# Swipe
A collection of activity extension methods to easily make any activity swipable:
@@ -182,20 +175,35 @@ Special thanks goes to the original project, [SwipeBackHelper](https://github.co
KAU's swipe is a Kotlin rewrite, along with support for all directions and weakly referenced contexts.
-<a name="timber-logger"></a>
+# Debounce
+
+Debouncing is a means of throttling a function so that it is called no more than once in a given instance of time.
+An example where you'd like this behaviour is the searchview; you want to deliver search results quickly,
+but you don't want to update your response with each new character.
+Instead, you can wait until a user finishes their query, then search for the results.
+
+Example:
+
+![Debounce 0](https://raw.githubusercontent.com/AllanWang/Storage-Hub/master/kau/kau_search_debounce_0.gif)
+![Debounce 500](https://raw.githubusercontent.com/AllanWang/Storage-Hub/master/kau/kau_search_debounce_500.gif)
+
+The first case is an example of no debouncing, whereas the second case is an example with a 500ms debounce.
+
+KAU offers extensions to easily convert or create functions into debouncables.
+Simply call `debounce` and specify your interval on an existing function, or with a new function.
+
+
## Timber Logger
[Timber](https://github.com/JakeWharton/timber)'s DebugTree uses the tag to specify the current class that is being logged.
To add the tag directly in the message, create an object that extends the TimberLogger class with the tag name as the argument.
Along with the timber methods (`v`, `i`, `d`, `e`), Timber Logger also supports `eThrow` to wrap a String in a throwable
-<a name="email-builder"></a>
## Email Builder
Easily send an email through `Context.sendEmail`.
Include your email and subject, along with other optional configurations such as retrieving device info.
-<a name="extensions"></a>
## Extension Functions
> "[Extensions](https://kotlinlang.org/docs/reference/extensions.html) provide the ability to extend a class with new functionality without having to inherit from the class"
@@ -204,7 +212,6 @@ Note that since KAU depends on [ANKO](https://github.com/Kotlin/anko), all of th
KAU's vast collection of extensions is one of its strongest features.
There are too many to explain here, but you may check out the [utils package](https://github.com/AllanWang/KAU/tree/master/core/src/main/kotlin/ca/allanwang/kau/utils)
-<a name="lazy-resettable></a>
## Lazy Resettable
In the spirit of Kotlin's Lazy delegate, KAU supports a resettable version. Calling `lazyResettable` produces the same delegate,
diff --git a/core/src/main/kotlin/ca/allanwang/kau/kotlin/Debouncer.kt b/core/src/main/kotlin/ca/allanwang/kau/kotlin/Debouncer.kt
new file mode 100644
index 0000000..4fba2c8
--- /dev/null
+++ b/core/src/main/kotlin/ca/allanwang/kau/kotlin/Debouncer.kt
@@ -0,0 +1,124 @@
+package ca.allanwang.kau.kotlin
+
+import ca.allanwang.kau.logging.KL
+import java.util.concurrent.Executors
+import java.util.concurrent.TimeUnit
+
+/**
+ * Created by Allan Wang on 2017-08-05.
+ *
+ * Thread safe function wrapper to allow for debouncing
+ * With reference to <a href="https://stackoverflow.com/a/20978973/4407321">Stack Overflow</a>
+ */
+
+/**
+ * The debouncer base
+ * Implements everything except for the callback,
+ * as the number of variables is different between implementations
+ * You may still use this without extending it, but you'll have to pass a callback each time
+ */
+open class Debouncer(var interval: Long) {
+ private val sched = Executors.newScheduledThreadPool(1)
+ private var task: DebounceTask? = null
+
+ /**
+ * Generic invocation to pass a callback to the new task
+ * Pass a new callback for the task
+ * If another task is pending, it will be invalidated
+ */
+ operator fun invoke(callback: () -> Unit) {
+ synchronized(this) {
+ task?.invalidate()
+ val newTask = DebounceTask(callback)
+ KL.v("Debouncer task created: $newTask in $this")
+ sched.schedule(newTask, interval, TimeUnit.MILLISECONDS)
+ task = newTask
+ }
+ }
+
+ /**
+ * Call to cancel all pending requests and shutdown the thread pool
+ * The debouncer cannot be used after this
+ */
+ fun terminate() = sched.shutdownNow()
+
+ /**
+ * Invalidate any pending tasks
+ */
+ fun cancel() {
+ synchronized(this) {
+ if (task != null) KL.v("Debouncer cancelled for $task in $this")
+ task?.invalidate()
+ task = null
+ }
+ }
+
+}
+
+/*
+ * Helper extensions for functions with 0 to 3 arguments
+ */
+
+/**
+ * The debounced task
+ * Holds a callback to execute if the time has come and it is still valid
+ * All methods can be viewed as synchronous as the invocation is synchronous
+ */
+private class DebounceTask(inline val callback: () -> Unit) : Runnable {
+ private var valid = true
+
+ fun invalidate() {
+ valid = false
+ }
+
+ override fun run() {
+ if (!valid) return
+ valid = false
+ KL.v("Debouncer task executed $this")
+ try {
+ callback()
+ } catch (e: Exception) {
+ KL.e(e, "DebouncerTask exception")
+ }
+ }
+}
+
+/**
+ * A zero input debouncer
+ */
+class Debouncer0 internal constructor(interval: Long, val callback: () -> Unit) : Debouncer(interval) {
+ operator fun invoke() = invoke(callback)
+}
+
+fun debounce(interval: Long, callback: () -> Unit) = Debouncer0(interval, callback)
+fun (() -> Unit).debounce(interval: Long) = debounce(interval, this)
+
+/**
+ * A one argument input debouncer
+ */
+class Debouncer1<T> internal constructor(interval: Long, val callback: (T) -> Unit) : Debouncer(interval) {
+ operator fun invoke(key: T) = invoke { callback(key) }
+}
+
+fun <T> debounce(interval: Long, callback: (T) -> Unit) = Debouncer1(interval, callback)
+fun <T> ((T) -> Unit).debounce(interval: Long) = debounce(interval, this)
+
+/**
+ * A two argument input debouncer
+ */
+class Debouncer2<T, V> internal constructor(interval: Long, val callback: (T, V) -> Unit) : Debouncer(interval) {
+ operator fun invoke(arg0: T, arg1: V) = invoke { callback(arg0, arg1) }
+}
+
+fun <T, V> debounce(interval: Long, callback: (T, V) -> Unit) = Debouncer2(interval, callback)
+fun <T, V> ((T, V) -> Unit).debounce(interval: Long) = debounce(interval, this)
+
+/**
+ * A three argument input debouncer
+ */
+class Debouncer3<T, U, V> internal constructor(interval: Long, val callback: (T, U, V) -> Unit) : Debouncer(interval) {
+ operator fun invoke(arg0: T, arg1: U, arg2: V) = invoke { callback(arg0, arg1, arg2) }
+}
+
+fun <T, U, V> debounce(interval: Long, callback: ((T, U, V) -> Unit)) = Debouncer3(interval, callback)
+fun <T, U, V> ((T, U, V) -> Unit).debounce(interval: Long) = debounce(interval, this)
diff --git a/core/src/main/kotlin/ca/allanwang/kau/kotlin/LazyResettable.kt b/core/src/main/kotlin/ca/allanwang/kau/kotlin/LazyResettable.kt
index 2ac5d2f..ceeaa30 100644
--- a/core/src/main/kotlin/ca/allanwang/kau/kotlin/LazyResettable.kt
+++ b/core/src/main/kotlin/ca/allanwang/kau/kotlin/LazyResettable.kt
@@ -13,7 +13,7 @@ internal object UNINITIALIZED
fun <T : Any> lazyResettable(initializer: () -> T): LazyResettable<T> = LazyResettable<T>(initializer)
-open class LazyResettable<T : Any>(private val initializer: () -> T, lock: Any? = null) : ILazyResettable<T>, Serializable {
+class LazyResettable<T : Any>(private val initializer: () -> T, lock: Any? = null) : ILazyResettable<T>, Serializable {
@Volatile private var _value: Any = UNINITIALIZED
private val lock = lock ?: this
diff --git a/core/src/main/kotlin/ca/allanwang/kau/logging/TimberLogger.kt b/core/src/main/kotlin/ca/allanwang/kau/logging/TimberLogger.kt
index 4c6d655..4cf566a 100644
--- a/core/src/main/kotlin/ca/allanwang/kau/logging/TimberLogger.kt
+++ b/core/src/main/kotlin/ca/allanwang/kau/logging/TimberLogger.kt
@@ -18,4 +18,7 @@ open class TimberLogger(tag: String) {
inline fun i(s: String) = Timber.i(TAG, s)
inline fun v(s: String) = Timber.v(TAG, s)
inline fun eThrow(s: String) = e(Throwable(s))
+// fun plant() {
+// Timber.plant(Timber.Tree())
+// }
} \ No newline at end of file
diff --git a/core/src/test/kotlin/ca/allanwang/kau/kotlin/DebounceTest.kt b/core/src/test/kotlin/ca/allanwang/kau/kotlin/DebounceTest.kt
new file mode 100644
index 0000000..12bc5a4
--- /dev/null
+++ b/core/src/test/kotlin/ca/allanwang/kau/kotlin/DebounceTest.kt
@@ -0,0 +1,53 @@
+package ca.allanwang.kau.kotlin
+
+import org.jetbrains.anko.doAsync
+import org.junit.Test
+import kotlin.test.assertEquals
+
+/**
+ * Created by Allan Wang on 2017-08-05.
+ */
+class DebounceTest {
+
+ @Test
+ fun basic() {
+ var i = 0
+ val debounce = debounce(20) { i++ }
+ assertEquals(0, i, "i should start as 0")
+ (1..5).forEach { debounce() }
+ Thread.sleep(50)
+ assertEquals(1, i, "Debouncing did not cancel previous requests")
+ }
+
+ @Test
+ fun basicExtension() {
+ var i = 0
+ val increment: () -> Unit = { i++ }
+ (1..5).forEach { increment() }
+ assertEquals(5, i, "i should be 5")
+ val debounce = increment.debounce(50)
+ (6..10).forEach { debounce() }
+ assertEquals(5, i, "i should not have changed")
+ Thread.sleep(100)
+ assertEquals(6, i, "i should increment to 6")
+ }
+
+ @Test
+ fun multipleDebounces() {
+ var i = 0
+ val debounce = debounce<Int>(10) { i += it }
+ debounce(1) //ignore -> i = 0
+ Thread.sleep(5)
+ assertEquals(0, i)
+ debounce(2) //accept -> i = 2
+ Thread.sleep(15)
+ assertEquals(2, i)
+ debounce(4) //ignore -> i = 2
+ Thread.sleep(5)
+ assertEquals(2, i)
+ debounce(8) //accept -> i = 10
+ Thread.sleep(15)
+ assertEquals(10, i)
+ }
+
+} \ No newline at end of file