Skip to content

Commit

Permalink
Refactor and test DeferredAction. (#355)
Browse files Browse the repository at this point in the history
  • Loading branch information
Laimiux authored Mar 15, 2024
1 parent 9c79e02 commit d565baa
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 14 deletions.
21 changes: 7 additions & 14 deletions formula/src/main/java/com/instacart/formula/DeferredAction.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ package com.instacart.formula
*/
class DeferredAction<Event>(
val key: Any,
val action: Action<Event>,
private val action: Action<Event>,
// We use event listener for equality because it provides better equality performance
val initial: (Event) -> Unit
private val initial: (Event) -> Unit
) {
private var cancelable: Cancelable? = null

internal var listener: (Event) -> Unit = initial
internal var cancelable: Cancelable? = null

internal fun start() {
cancelable = action.start() { message ->
Expand All @@ -24,22 +24,15 @@ class DeferredAction<Event>(
cancelable = null
}

/**
* Action equality is based on the [initial] listener.
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false

other as DeferredAction<*>

if (initial != other.initial) return false

return true
return other is DeferredAction<*> && initial == other.initial
}

override fun hashCode(): Int {
return initial.hashCode()
}

fun keyAsString(): String {
return key.toString()
}
}
31 changes: 31 additions & 0 deletions formula/src/test/java/com/instacart/formula/DeferredActionTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.instacart.formula

import com.google.common.truth.Truth.assertThat
import org.junit.Test

class DeferredActionTest {

@Test
fun `identity equality returns true`() {
val callback = { _: Unit -> }
val action = DeferredAction(key = "1", action = Action.onInit(), callback)
assertThat(action.equals(action)).isTrue()
}

@Test
fun `when class is different, equality returns false`() {
val callback = { _: Unit -> }
val action = DeferredAction(key = "1", action = Action.onInit(), callback)
assertThat(action).isNotEqualTo("string")
}

@Test
fun `when listeners are not equal, the actions are not equal`() {
val callback = { _: Unit -> }
val callback2 = { _: Unit -> }
val action1 = DeferredAction(key = "1", action = Action.onInit(), callback)
val action2 = DeferredAction(key = "1", action = Action.onInit(), callback2)

assertThat(action1).isNotEqualTo(action2)
}
}

0 comments on commit d565baa

Please sign in to comment.