Skip to content

Commit

Permalink
Merge pull request #23 from polytypic/fix/make-startWith-callable-fro…
Browse files Browse the repository at this point in the history
…m-any-thread

Fix: Make startWith callable from any thread
  • Loading branch information
adibfara authored Apr 24, 2020
2 parents b30c647 + b5fcaf5 commit 571e317
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ package com.snakydesign.livedataextensions

import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import com.snakydesign.livedataextensions.livedata.SingleLiveData
import com.snakydesign.livedataextensions.operators.SingleLiveDataConcat
import java.util.concurrent.atomic.AtomicBoolean
Expand Down Expand Up @@ -46,10 +47,19 @@ fun <T> merge(liveDataList: List<LiveData<T>>): LiveData<T> {
* Emits the `startingValue` before any other value.
*/
fun <T> LiveData<T>.startWith(startingValue: T?): LiveData<T> {
val finalLiveData: MediatorLiveData<T> = MediatorLiveData()
finalLiveData.value = startingValue
finalLiveData.addSource(this) { source ->
finalLiveData.value = source
val finalLiveData = MediatorLiveData<T>()
var startingData: LiveData<T>? = MutableLiveData(startingValue)
finalLiveData.addSource(this) {
if (null != startingData) {
finalLiveData.removeSource(startingData!!)
startingData = null
}
finalLiveData.value = it
}
finalLiveData.addSource(startingData!!) {
finalLiveData.value = it
finalLiveData.removeSource(startingData!!)
startingData = null
}
return finalLiveData
}
Expand Down
2 changes: 1 addition & 1 deletion versions.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ ext.versionNumbers = [

kotlin : '1.3.20',
mockito : '2.21.0',
arch : '2.0.0',
arch : '2.1.0',
junit : '4.12',

minSdk : 16,
Expand Down

0 comments on commit 571e317

Please sign in to comment.