xxfast / KStore

A tiny Kotlin multiplatform library that assists in saving and restoring objects to and from disk using kotlinx.coroutines, kotlinx.serialisation and kotlinx.io
https://xxfast.github.io/KStore/
Apache License 2.0
542 stars 18 forks source link

Add StateFlow and MutableStateFlow support #109

Closed robertjamison closed 3 months ago

robertjamison commented 5 months ago

Flows require the direct statement of a CoroutineScope , stateIn, or collect() to properly access the data in a composable's LaunchedEffect. This is a lot of effort, and Flows are considered a cold state once completed.

Based on JetBrains' shift towards StateFlow and SharedFlow, I recommend adding a way to use both of these datatypes to the API, as well as their mutable versions a feature of the next update.

xxfast commented 5 months ago

Hi!. Do you mean changing the KStore's updates from Flow<T> to StateFlow<T>?

robertjamison commented 5 months ago

Yes, but after a lot of thought, I think an easier option would be to include an example of how you properly generate a StateFlow<T> from the Flow<T> that KStore already outputs from store.update. It could be even as simple as linking to the page I sent before in the README.

xxfast commented 5 months ago

Hi @robertjamison.

I have some examples in my NYTimes app - but in that case I'm using molecule, so it might not work for your usecase

Coversion to StateFlow should be easy but requires some configurations to be made from the use-site

val playerFlow: StateFlow<Player?> = userStore.updates.stateIn(coroutineScope, SharingStarted.Lazily, null)

Here I'm making the following configurations

  1. the StateFlow will contain null as the initial value before the store is read. I usually tend to represent this as a Loading state
    val Loading: Nothing? = null
    val playerFlow: StateFlow<Player?> = userStore.updates.stateIn(coroutineScope, SharingStarted.Lazily, Loading)
  2. Sharing strategy here is Lazy
  3. You will need to provide a coroutine scope