Last active
May 15, 2023 14:10
-
-
Save guness/0a96d80bc1fb969fa70a5448aa34c215 to your computer and use it in GitHub Desktop.
LiveData merger that takes two live data inputs and a merger function. Merges two results using merger function, and returning result allowing null inputs and outputs. Input and out types are parametric. However only supports two live data inputs for now.
This file contains 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
import androidx.annotation.NonNull; | |
import androidx.lifecycle.LiveData; | |
import androidx.lifecycle.MediatorLiveData; | |
import androidx.lifecycle.Observer; | |
import java.util.function.BiFunction; | |
public class CombinedLiveData<T, K, S> extends MediatorLiveData<S> { | |
private T data1; | |
private K data2; | |
public CombinedLiveData(LiveData<T> source1, LiveData<K> source2, BiFunction<T, K, S> combine) { | |
super.addSource(source1, it -> { | |
data1 = it; | |
setValue(combine.apply(data1, data2)); | |
}); | |
super.addSource(source2, it -> { | |
data2 = it; | |
setValue(combine.apply(data1, data2)); | |
}); | |
} | |
@Override | |
public <S1> void addSource(@NonNull LiveData<S1> source, @NonNull Observer<? super S1> onChanged) { | |
throw new UnsupportedOperationException(); | |
} | |
@Override | |
public <S1> void removeSource(@NonNull LiveData<S1> toRemote) { | |
throw new UnsupportedOperationException(); | |
} | |
} |
This file contains 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
import androidx.lifecycle.LiveData | |
import androidx.lifecycle.MediatorLiveData | |
import androidx.lifecycle.Observer | |
class CombinedLiveData<T, K, S>(source1: LiveData<T>, source2: LiveData<K>, private val combine: (data1: T?, data2: K?) -> S) : MediatorLiveData<S>() { | |
private var data1: T? = null | |
private var data2: K? = null | |
init { | |
super.addSource(source1) { | |
data1 = it | |
value = combine(data1, data2) | |
} | |
super.addSource(source2) { | |
data2 = it | |
value = combine(data1, data2) | |
} | |
} | |
override fun <T : Any?> addSource(source: LiveData<T>, onChanged: Observer<in T>) { | |
throw UnsupportedOperationException() | |
} | |
override fun <T : Any?> removeSource(toRemote: LiveData<T>) { | |
throw UnsupportedOperationException() | |
} | |
} |
ghost
commented
Apr 19, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment