Skip to content

Commit b8d6c01

Browse files
committed
Reduced observable subscription overhead
1 parent 9e490a2 commit b8d6c01

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/shared/observables/StateObservableExtensions.kt

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,26 @@
11
package com.lasthopesoftware.bluewater.shared.observables
22

33
import androidx.compose.runtime.Composable
4+
import androidx.compose.runtime.DisposableEffect
45
import androidx.compose.runtime.LaunchedEffect
56
import androidx.compose.runtime.MutableState
67
import androidx.compose.runtime.State
78
import androidx.compose.runtime.mutableStateOf
89
import androidx.compose.runtime.remember
910
import androidx.compose.runtime.snapshotFlow
1011
import kotlinx.coroutines.flow.drop
11-
import kotlinx.coroutines.rx3.asFlow
1212
import kotlinx.coroutines.withContext
1313
import kotlin.coroutines.CoroutineContext
1414
import kotlin.coroutines.EmptyCoroutineContext
1515

1616
@Composable
17-
fun <T, S : InteractionState<T>> S.subscribeAsState(
18-
context: CoroutineContext = EmptyCoroutineContext
19-
): State<T> = updatingState(context)
17+
fun <T, S : InteractionState<T>> S.subscribeAsState(): State<T> = updatingState()
2018

2119
@Composable
2220
fun <T, S : MutableInteractionState<T>> S.subscribeAsMutableState(
2321
context: CoroutineContext = EmptyCoroutineContext
2422
): MutableState<T> {
25-
val state = updatingState(context)
23+
val state = updatingState()
2624

2725
LaunchedEffect(key1 = this, context) {
2826
if (context == EmptyCoroutineContext) {
@@ -39,17 +37,15 @@ fun <T, S : MutableInteractionState<T>> S.subscribeAsMutableState(
3937
}
4038

4139
@Composable
42-
private fun <T, S : InteractionState<T>> S.updatingState(context: CoroutineContext): MutableState<T> {
40+
private fun <T, S : InteractionState<T>> S.updatingState(): MutableState<T> {
4341
val state = remember { mutableStateOf(value) }
44-
LaunchedEffect(this, context) {
45-
if (context == EmptyCoroutineContext) {
46-
asFlow().collect {
47-
state.value = it.value
48-
}
49-
} else withContext(context) {
50-
asFlow().collect {
51-
state.value = it.value
52-
}
42+
DisposableEffect(this) {
43+
val subscription = subscribe {
44+
state.value = it.value
45+
}
46+
47+
onDispose {
48+
subscription.dispose()
5349
}
5450
}
5551
return state

0 commit comments

Comments
 (0)