https://kotlinlang.org logo
Title
l

Luc Girardin

04/26/2023, 10:01 PM
I am trying to convert values collected from a Kotlin Flow to a state variable (or whatever other React hook is appropriate to trigger update). Did maybe one of you succeeded at integrating the features of Kotlin Flows with React?!?
My immediate use case is to debounce events, where I think Flows would be very well suited. Or are you all using Lodash for that purpose?
t

turansky

04/27/2023, 8:09 PM
Flow
is fine, 2-3 additional common hooks required to simplify
Flow
usage
m

Mike Dawson

04/30/2023, 6:05 PM
I use this at the moment:
fun <T> Flow<T>.collectAsState(
    initialState: T,
): StateInstance<T> {
    val state = useState { initialState }

    useEffect(dependencies = arrayOf(this)) {
        val coroutineScope = CoroutineScope(Dispatchers.Main + Job())

        coroutineScope.launch {
            this@collectAsState.collect {
                state.component2().invoke(it)
            }
        }

        cleanup {
            coroutineScope.cancel()
        }
    }

    return state
}
t

turansky

05/01/2023, 8:20 PM
It doesn’t look safe 😞
l

Luc Girardin

05/10/2023, 3:32 PM
@Mike Dawson Many thanks for the input (and sorry for the delayed reply): this do look brilliant to me and exactly what I needed. @turansky What makes you believe this is unsafe? Any tip on how to improve this piece of code?!?
t

turansky

05/10/2023, 3:33 PM
It must be hooks
Otherwise it looks like you can call it optionally
l

Luc Girardin

05/10/2023, 3:35 PM
I know I am a React rookie in comparison to you: aren’t useState and useEffect hooks?!?
t

turansky

05/10/2023, 3:37 PM
Now we discuss hooks with following contracts:
fun useAsyncEffect(
   vararg dependencies: Any?
   block: suspend CoroutineScope.() -> Unit,
)
where it will be possible to create flows
And one more for “async” state
l

Luc Girardin

05/10/2023, 3:47 PM
I am slowly starting to get it. Need to read some more on this useAsyncEffect hook. There is no such implementation for Kotlin, right?
t

turansky

05/14/2023, 1:13 PM
Initial
useAsyncEffect
implementation is here
Released in
pre.549
m

Mike Dawson

05/15/2023, 7:13 AM
I think it is safe... I'm not sure it's the most efficient way of doing things (e.g. creating / canceling a coroutine scope each time the flow changes - but that doesn't happen very often - normally we are collecting values from the same flow). Cleanup of the previous effect always runs before the effect runs again, so the old coroutine is always cancelled first. Technically, this returns a read/write state instance, it might be better to return the value ready-only.
Having a standard useAsyncEffect is definitely nice