Skip to content

Commit

Permalink
Ensure distinctUntilChanged handle observers that mutate source LiveData
Browse files Browse the repository at this point in the history
`latestValue = it` is executed only after new value is set to Mediator. This gives
observers possibilty to set new value to source LiveData before that assigment
is executed.

Luckily, LiveData handles this case by invalidating current dispatch of source
LiveData, and not dispatching immediately so currently everything works correctly.

I'm adding this test case to catch future regression, if LiveData behavior changes.
  • Loading branch information
NemanjaBozovic-TomTom committed Feb 12, 2019
1 parent 78d1e7e commit aabf536
Showing 1 changed file with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import android.arch.lifecycle.Observer
import org.junit.*
import org.mockito.Mockito
import org.mockito.Mockito.times
import java.lang.IllegalStateException
import kotlin.test.assertEquals

/**
Expand Down Expand Up @@ -98,6 +99,25 @@ class FilteringTest {
Mockito.verifyNoMoreInteractions(observer)
}

@Test
fun `test LiveData distinctUntilChanged updating source from observer doesn't trigger change`() {
val sourceLiveData = MutableLiveData<Int>()
var timesCalled = 0
val observer = Observer<Int> { t ->
timesCalled++
// set same value from observer
sourceLiveData.value = t
}
val testingLiveData = sourceLiveData.distinctUntilChanged()
testingLiveData.observeForever(observer)

sourceLiveData.value = 2

if (timesCalled > 1) {
throw IllegalStateException()
}
}

@Test
fun `test LiveData distinctUntilChanged`(){
val observer= Mockito.mock(Observer::class.java) as Observer<Int>
Expand Down

0 comments on commit aabf536

Please sign in to comment.