icerockdev / moko-kswift

Swift-friendly api generator for Kotlin/Native frameworks
https://moko.icerock.dev
Apache License 2.0
351 stars 21 forks source link

Flow and StateFlow generics support for Swift #27

Open Alex009 opened 2 years ago

Alex009 commented 2 years ago

just like mvvm-livedata we need support of coroutines Flow out of box. for iOS we need class-wrapper to save generic type and we need in iosMain generation of this class-wrapper accessors. example:

commonMain

class MyViewModel: ViewModel() {
    val login: MutableStateFlow<String> = MutableStateFlow("")
    val isLoginEnabled: Flow<Boolean> = login.map { it.isNotEmpty() }
}

iosMain

class CMutableStateFlowOpt<T>(private val wrapped: MutableStateFlow<T>): MutableStateFlow<T> by wrapped {
    fun observe(block: (T) -> Unit): Closeable { ... }
}

class CMutableStateFlow<T: Any>(wrapped: MutableStateFlow<T>): CMutableStateFlowOpt<T>(wrapped)

class CStateFlowOpt<T>(private val wrapped: StateFlow<T>): StateFlow<T> by wrapped {
    fun observe(block: (T) -> Unit): Closeable { ... }
}

class CStateFlow<T: Any>(wrapped: StateFlow<T>): CStateFlowOpt<T>(wrapped)

class CFlowOpt<T>(private val wrapped: Flow<T>): Flow<T> by wrapped {
    fun observe(block: (T) -> Unit): Closeable { ... }
}

class CFlow<T: Any>(wrapped: Flow<T>): CFlowOpt<T>(wrapped)

iosMain (autogenerated by compiler plugin - need to be developed in this isue)

val MyViewModel.loginWrapped: CMutableStateFlow<String> = CMutableStateFlow(login)
val MyViewModel.isLoginEnabledWrapped: CFlow<Boolean> = CFlow(isLoginEnabled)

as result in swift we will see:

class MyViewModel: ViewModel() {
    let login: MutableStateFlow
    let loginWrapped: CMutableStateFlow<NSString>
    let isLoginEnabled: Flow
    let isLoginEnabledWrapped: CFlow<KotlinBoolean>
}
Alex009 commented 2 years ago

for now can be used https://github.com/rickclephas/KMP-NativeCoroutines