rickclephas / KMP-NativeCoroutines

Library to use Kotlin Coroutines from Swift code in KMP apps
MIT License
1.07k stars 32 forks source link

Is it possible to use shared flows with onChange and onReceive modifiers? #184

Closed osrl closed 3 months ago

osrl commented 3 months ago

I have this flows in my kotlin code:

    private val _event1 = MutableStateFlow(false)
    @NativeCoroutinesState
    val event1 = _event1

    private val _event2 = MutableSharedFlow<Boolean>()
    @NativeCoroutines
    val event2 = _event2

But I can't use shared flow on my swift code.

Screenshot 2024-08-07 at 13 12 48

I also tried without $. Is it possible to use shared flows with onChange and onReceive modifiers?

osrl commented 3 months ago

For a workaround, I used .task and asyncSequence function

rickclephas commented 3 months ago

onChange only requires a value, which is why it's working for your @NativeCoroutinesState property. A SharedFlow doesn't have a single value, but it does have a replayCache. You could try and use that as the value:

.onChange(of: eventDispatcher.event2ReplayCache) { event in }

onReceive requires a Combine Publisher. You can create a publisher for any kind of flow:

let publisher = createPublisher(for: eventDispatcher.event2)

One thing to be aware of is that this will create a new publisher and therefore a new Flow collection every time. So you would probably need to store this publisher in a viewmodel or something instead of calling the createPublisher(for:) function in your SwiftUI body.