https://kotlinlang.org logo
Title
y

Yuri

08/15/2019, 11:13 PM
Hey guys, I’m trying to migrate RxJava code dealing with Android SharedPreferences to Kotlin Flow. How correct migration should look like?
private val keyChangesObservable: Observable<String>

  init {
    keyChangesObservable = io.reactivex.Observable.create(ObservableOnSubscribe<String> { emitter ->
      val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> emitter.onNext(key) }
      emitter.setCancellable { prefs.unregisterOnSharedPreferenceChangeListener(listener) }
      prefs.registerOnSharedPreferenceChangeListener(listener)
    }).share()
  }
p

Pablichjenkov

08/16/2019, 2:35 AM
Quick Question at Louis, is
runCatching{ offer(event)}
picking up any exception thrown all the way down the Flow stream. Or just catching the operation of offering the event to some EventQueue. What would be the difference of using send(...)?
g

gildor

08/16/2019, 3:01 AM
runCatching in this case would just swallow exception
p

Pablichjenkov

08/16/2019, 3:42 AM
That’s right but what exception? Any Exception all the way down the stream? It does not look like so. It looks like is just to guard against possible ClosedChannel exceptions but nothing else, is that it?
g

gildor

08/16/2019, 3:45 AM
yes, it’s probably against closedchannel exception
actually not sure that it needed here, channel is closed on flow cancellation in this example and unregister listener, so it should be safe
p

Pablichjenkov

08/16/2019, 3:48 AM
🤔
l

louiscad

08/16/2019, 6:15 AM
It should be safe, but I'm not sure and I've been bitten by this throwing unexpectedly in others use cases using Channels in the past, so I'm guarding myself against this bad design until kotlinx.coroutines provides an alternative. I opened an issue for that a while ago: https://github.com/Kotlin/kotlinx.coroutines/issues/974