AmrJyniat
03/24/2023, 1:50 PMJohn O'Reilly
03/24/2023, 1:51 PMAmrJyniat
03/24/2023, 3:16 PMTextField
with let
variable in SwiftUI, because TextField needs @State
or @Binding
as a value which the mentioned way doesn’t provide, does this library solves the mentioned issue?Anonymike
03/24/2023, 5:34 PMAnonymike
03/24/2023, 5:47 PM// Kotlin : KMMViewModel Class
class CommunicationScreenViewModel : KMMViewModel(), KoinComponent {
// Singleton ViewModel providing data we wish to hold for the life of the app
val communication: CommunicationViewModel = get()
// Mutable state list of conversations
@NativeCoroutinesState
val conversations = MutableStateFlow<List<Conversation>(viewModelScope, emptyList())
// Mutable state computed from conversation to show the count for example
@NativeCoroutinesState
val conversationCount = communication.conversations.map { it.size }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), 0)
}
// Swift : Get an instance (however you prefer, we use Koin) as an Observed model
@ObservedViewModel private var model: CommunicationScreenViewModel = koin.get()
You can then use the view model object properties as is model.conversations
for example in your swift views. The one quirk we have not overcome is we don't get any code completion for the state properties (they are generated as extension properties by KMP under the hood with @Objcname for the name). Coroutines work beautifully with code completion and Task / await though.
I would personally appreciate it if anyone knows how to get code completion for the state properties or at least confirmation that there is no way for it to work yet.
I hope this helps!AmrJyniat
03/24/2023, 8:51 PMAnonymike
03/24/2023, 9:14 PMenvironmentObject
and @EnvironmentViewModel
provided by KMMViewModel seems to work well instead of using koin to get the instance in two separate places so you don't have this issue (you don't make the kotlin <-> swift jump twice with the same instance).
We also found that some "application" ViewModels appropriately share the same data with more than one "screen" ViewModel. In those cases the singleton application view model is never directly used outside of shared code. The screen view models used in swift can then share that data using the stateIn methods so you have as many instances of the screen view model as you need and never have the issue there.
Primarily, this was just a limitation that we had to learn the workarounds for that we believe has more to do with the way Kotlin / Swift integrate than anything.Anonymike
03/24/2023, 9:17 PMAmrJyniat
03/25/2023, 8:54 AMenvironmentObject
and @EnvironmentViewModel
. is that correct?
And do you have an open source project uses this way?Anonymike
03/25/2023, 9:03 PM