ursus
04/30/2021, 12:50 AMclass AppInForeground {
val appInForeground: Observable<Boolean> by lazy {
Lifecycle.wrapAsObservable()
.distinctUntilChanged()
.publish()
.replay(1)
}
}
naive Flow implementation
class AppInForeground {
fun appInForeground(scope: CoroutineScope) {
if (_appInForeground == null) {
synchornized(this) {
if(_appInForeground == null) {
_appInForeground = Lifecycle.wrapAsFlow()
.distinctUntilChanged()
.shareIn(scope, SharingStarted.Lazily, 1)
}
}
}
return _appInForeground!!
}
}
just looks stupid, however the main issue is that callers should not determine the scope, right?
I think idiomatic way is this
class AppInForeground : HasLifecycle {
private val scope = SupervisorScope(..)
private val _appInForeground = MutableStateFlow(false)
val appInForeground: Flow<Boolean> get() = _appInForeground
override fun create() {
scope.launch {
Lifecycle.wrapAsFlow()
.distinctUntilChanged()
.collect {
_appInForeground.value = it
}
}
}
override fun destroy() {
scope.cancel()
}
}
Works, however its a bit less efficient, i.e. it subscribers when the AppInForeground class si instantiated, also whole lot more ceremony...
Is there a way more close to the rx way? or should I just deal with it?uli
04/30/2021, 8:18 AM_appInForeground
is volatile
https://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.htmlursus
04/30/2021, 12:13 PM