Skip to content

Instantly share code, notes, and snippets.

@kursor1337
Last active November 13, 2023 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kursor1337/e33ba8a5d73c53c3d816678b7d289f02 to your computer and use it in GitHub Desktop.
Save kursor1337/e33ba8a5d73c53c3d816678b7d289f02 to your computer and use it in GitHub Desktop.
CFlow KMP
open class CFlow<T : Any>(private val flow: Flow<T>) : Flow<T> by flow
@Suppress("DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE")
open class CStateFlow<T : Any>(private val stateFlow: StateFlow<T>) : CFlow<T>(stateFlow), StateFlow<T> by stateFlow
@Suppress("DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE")
class CMutableStateFlow<T : Any>(
private val mutableStateFlow: MutableStateFlow<T>
) : CStateFlow<T>(mutableStateFlow), MutableStateFlow<T> by mutableStateFlow {
constructor(initialValue: T) : this(MutableStateFlow(initialValue))
}
interface Cancelable {
fun cancel()
}
open class FlowWrapper<T>(
private val flow: Flow<T>
) {
fun collect(consumer: (T) -> Unit): Cancelable {
val scope = CoroutineScope(Dispatchers.Main.immediate)
flow
.onEach { consumer(it) }
.launchIn(scope)
return object : Cancelable {
override fun cancel() {
scope.cancel()
}
}
}
}
public class ObservableState<T: AnyObject>: ObservableObject {
@Published var value: T
private var cancelable: Cancelable?
init(_ state: CStateFlow<T>) {
value = state.value
cancelable = FlowWrapper<T>(flow: state).collect(
consumer: { [weak self] value in
if let value {
self?.value = value
}
}
)
}
func recreate(_ state: CStateFlow<T>) {
cancelable?.cancel()
cancelable = FlowWrapper<T>(flow: state).collect(
consumer: { [weak self] value in
if let value {
self?.value = value
}
}
)
}
deinit {
self.cancelable?.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment