-
-
Save kursor1337/e33ba8a5d73c53c3d816678b7d289f02 to your computer and use it in GitHub Desktop.
CFlow KMP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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