|
| 1 | +package functional |
| 2 | + |
| 3 | +import org.junit.Test |
| 4 | +import kotlin.test.assertEquals |
| 5 | + |
| 6 | +class ObservableValue<T>(initial: T) { |
| 7 | + var value: T = initial |
| 8 | + |
| 9 | + fun observe(observer: (T) -> Unit) { |
| 10 | + TODO() |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +class ObservableValueTest { |
| 15 | + |
| 16 | + @Test |
| 17 | + fun `should behave like regular value`() { |
| 18 | + val i = ObservableValue<Int?>(null) |
| 19 | + assertEquals(null, i.value) |
| 20 | + i.value = 1 |
| 21 | + assertEquals(1, i.value) |
| 22 | + i.value = 2 |
| 23 | + assertEquals(2, i.value) |
| 24 | + } |
| 25 | + |
| 26 | + @Test |
| 27 | + fun `should call observer when value changes`() { |
| 28 | + val o = ObservableValue<String>("A") |
| 29 | + val called = mutableListOf<String>() |
| 30 | + o.observe { called += it } |
| 31 | + o.value = "B" |
| 32 | + o.value = "C" |
| 33 | + o.value = "D" |
| 34 | + assertEquals(listOf("B", "C", "D"), called) |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + fun `should call observers when value changes`() { |
| 39 | + val o1 = ObservableValue<String>("A") |
| 40 | + val o2 = ObservableValue<String>("A") |
| 41 | + val history1 = mutableListOf<String>() |
| 42 | + o1.observe { history1 += it } |
| 43 | + o1.value = "B" |
| 44 | + val history2 = mutableListOf<String>() |
| 45 | + o1.observe { history2 += it } |
| 46 | + val history3 = mutableListOf<String>() |
| 47 | + o2.observe { history3 += it } |
| 48 | + o1.value = "C" |
| 49 | + o1.value = "D" |
| 50 | + assertEquals(listOf("B", "C", "D"), history1) |
| 51 | + assertEquals(listOf("C", "D"), history2) |
| 52 | + assertEquals(listOf(), history3) |
| 53 | + } |
| 54 | +} |
0 commit comments