Last active
April 8, 2021 08:55
-
-
Save mohamed-khaled-hsn/a7d4194a8769a88069dc765a8441478e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @return [LiveData] with value produced from combining [source1] and [source2] using [combiner] | |
* | |
* This function produces new value only if [source1] and [source2] values are not null | |
*/ | |
fun <T1, T2, R> combineNonNull( | |
source1: LiveData<T1>, | |
source2: LiveData<T2>, | |
combiner: (T1, T2) -> R | |
): LiveData<R> { | |
val mediator = MediatorLiveData<R>() | |
val combinerFunction = { | |
val source1Value = source1.value | |
val source2Value = source2.value | |
if (source1Value != null && source2Value != null) { | |
mediator.value = combiner(source1Value, source2Value) | |
} | |
} | |
mediator.addSource(source1) { combinerFunction() } | |
mediator.addSource(source2) { combinerFunction() } | |
return mediator | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LiveDataExtensionKtTest { | |
@get:Rule | |
val instantTaskExecutorRule = InstantTaskExecutorRule() | |
@Test | |
fun `verify combine successfully combines values from sources`() { | |
val liveData1 = mutableLiveDataOf<Int>() | |
val liveData2 = mutableLiveDataOf<Int>() | |
val resultLiveData = combineNonNull(liveData1, liveData2) { | |
source1, source2 -> source1 + source2 | |
} | |
liveData1.value = 2 | |
liveData2.value = 2 | |
val result = resultLiveData.await() | |
assertThat(result).isEqualTo(4) | |
} | |
@Test | |
fun `verify combine result is null when one of the sources value is null`() { | |
val liveData1 = mutableLiveDataOf<Int>() | |
val liveData2 = mutableLiveDataOf<Int>() | |
val resultLiveData = combineNonNull(liveData1, liveData2) { | |
source1, source2 -> source1 + source2 | |
} | |
liveData1.value = 2 | |
// liveData2 didn't emit any values so its value is null | |
val result = resultLiveData.await() | |
assertThat(result).isNull() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
🔥