Skip to content

Commit

Permalink
Fixes #1: handle the case when the channel we are offering an item to…
Browse files Browse the repository at this point in the history
… is closed (#11)
  • Loading branch information
AChep committed Feb 22, 2021
1 parent e6f26b7 commit 8c8556f
Showing 1 changed file with 7 additions and 1 deletion.
Expand Up @@ -3,6 +3,7 @@ package com.tfcporciuncula.flow
import android.content.SharedPreferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
Expand All @@ -17,11 +18,16 @@ class FlowSharedPreferences @JvmOverloads constructor(
) {

internal val keyFlow: KeyFlow = callbackFlow {
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> offer(key) }
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> offerCatching(key) }
sharedPreferences.registerOnSharedPreferenceChangeListener(listener)
awaitClose { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener) }
}

// https://github.com/Kotlin/kotlinx.coroutines/issues/974
private fun <E> SendChannel<E>.offerCatching(element: E): Boolean {
return runCatching { offer(element) }.getOrDefault(false)
}

@JvmOverloads
fun getInt(key: String, defaultValue: Int = 0): Preference<Int> =
IntPreference(key, defaultValue, keyFlow, sharedPreferences, coroutineContext)
Expand Down

0 comments on commit 8c8556f

Please sign in to comment.