Skip to content

Instantly share code, notes, and snippets.

View jonas-m-'s full-sized avatar

Jonas Masalskis jonas-m-

View GitHub Profile
@jonas-m-
jonas-m- / AtomicMutableLiveData.kt
Created February 27, 2020 22:57
Atomic MutableLiveData implementation, allowing to post new value based on the current value in a thread-safe manner
/**
* A [MutableLiveData] which enables computing the new state from the current one
* and updating it atomically
*/
class AtomicMutableLiveData<T>(initialValue: T) : MutableLiveData<T>() {
private val state = AtomicReference<T>(initialValue)
init {
super.postValue(initialValue)
}
@jonas-m-
jonas-m- / CombineLatest.kt
Last active January 13, 2020 12:36
RxJava's combineLatest operator for Kotlin coroutines, designed for combining 2 ReceiveChannels
/**
* @return a channel, that will emit an item when either the [first] or [second] source channel emits a value.
* The emitted value will be a [Pair] containing most recently emitted values from both source channels.
*
* Either of the [Pair]'s values could be null, meaning, that the source channel, which is responsible for this value, hasn't emitted anything yet.
*/
fun <T> CoroutineScope.combineLatest(
first: ReceiveChannel<T>,
second: ReceiveChannel<T>
): ReceiveChannel<Pair<T?, T?>> = Channel<Pair<T?, T?>>().also { channel ->
@jonas-m-
jonas-m- / LiveDataExt.kt
Last active January 11, 2020 21:34
Convert LiveData<T> to Kotlin coroutines' ReceiveChannel<T>
/**
* @return a [ReceiveChannel] with a capacity of 1, which will emit every time the given [liveData] emits a value
*/
fun <T> CoroutineScope.channelOf(liveData: LiveData<T>) = produce(capacity = 1) {
val observer: Observer<T> = Observer {
if (it != null) {
offer(it)
}
}
@jonas-m-
jonas-m- / BackendApi.kt
Last active July 21, 2019 15:34
Example of implementing Repository using RxJava, backed by remote API and cached in memory. Contains functionality for fetching the list of data, deleting one item and reloading the cached list by repeating the remote API call
package example.rx
class BackendApi {
fun fetchUsers() = listOf(
User(420),
User(421),
User(422)
)
fun deleteUser(user: User) {
@jonas-m-
jonas-m- / build.gradle
Last active September 18, 2018 20:26
Android Gradle task for installing androidTestUtil dependencies: support test services & test orchestrator APKs
dependencies {
androidTestUtil 'com.android.support.test:orchestrator:1.0.2'
}
task installTestUtils() {
doFirst {
// Resolve and install all files associated with androidTestUtil configuration, which will be both - test services and the orchestrator APKs
configurations.androidTestUtil.resolvedConfiguration.files.forEach { filePath ->
println "Installing ${filePath} ..."
exec {