Skip to content

Instantly share code, notes, and snippets.

@aartikov
Created December 14, 2022 09:29
Show Gist options
  • Save aartikov/460a6ee7fa2e6e69c0a8f04d5d1e1fe0 to your computer and use it in GitHub Desktop.
Save aartikov/460a6ee7fa2e6e69c0a8f04d5d1e1fe0 to your computer and use it in GitHub Desktop.
Converts Decompose Value to StateFlow
fun <T : Any> Value<T>.toStateFlow(lifecycle: Lifecycle): StateFlow<T> {
val state = MutableStateFlow(this.value)
if (lifecycle.state != Lifecycle.State.DESTROYED) {
val observer = { value: T -> state.value = value }
subscribe(observer)
lifecycle.doOnDestroy {
unsubscribe(observer)
}
}
return state
}
@Dggsgwg
Copy link

Dggsgwg commented Dec 5, 2024

There is no unsubscribe function (at least in newer versions of Decompose). You may consider using this implementation instead:

fun <T : Any> Value<T>.toStateFlow(lifecycle: Lifecycle): StateFlow<T> {
    val state = MutableStateFlow(this.value)

    if (lifecycle.state != Lifecycle.State.DESTROYED) {
        val observer = { value: T -> state.value = value }
        val cancellation = subscribe(observer)
        lifecycle.doOnDestroy {
            cancellation.cancel()
        }
    }

    return state
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment