https://kotlinlang.org logo
#compose
Title
# compose
n

nitrog42

05/04/2022, 1:57 PM
Another question about the new
SavedStateHandle.saveable
API, is there an equivalent to
Copy code
val argArticleId = savedStateHandle.getStateFlow(ArticleArgKey, -1)
that return a State ? I tried with
.saveable(ArticleArgKey)
but it seems the return value is a Bundle instead of a Long... (in my case)
i

Ian Lake

05/04/2022, 2:47 PM
If you have a StateFlow, you call collectAsState() to make it into State. That is true for SavedStateHandle and for any other StateFlow.
n

nitrog42

05/04/2022, 2:47 PM
yes for collectAsState(), but I meant more as having directly a State in the ViewModel
I’m starting to use more and more MutableState in my ViewModels instead of StateFlow and... I kinda like it 😄
i

Ian Lake

05/04/2022, 2:49 PM
You have the SavedStateHandle itself in the ViewModel, you don't need a StateFlow or State for working with that
Maybe you could explain what you're trying to do?
n

nitrog42

05/04/2022, 2:57 PM
well nothing really interesting 😄 basically, here is a sample viewmodel :
Copy code
@HiltViewModel
class MyViewModel @Inject constructor(
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {
    val someItemId: StateFlow<Long> = savedStateHandle.getStateFlow(ItemIdArg, -1L)

    /**
     * Some State
     */
    var someState: SomeState by mutableStateOf(SomeState())
        private set

    /**
     * Some state for the UI
     */
    var someSavedState: SomeState by savedStateHandle.saveable(key = "SomeState", stateSaver = SomeState.Saver, init = {
        mutableStateOf(
            SomeState()
        )
    })
        private set
}
We can expose the state either through
mutableStateOf
directly, or use the new
saveable
api to get it saved in the `SavedStateHandle`/`rememberSaveable` now my Screen receive an arg through Navigation, let’s say a `detailId`; You can get this arg using simply
handle.getStateFlow(ArgKey)
and I was wondering if there was a similar helper that returns a Compose
State<>
/
MutableState<>
(so we can use it directly from a
Composable
, or use it in the
ViewModel
, the same as the
SomeState
I have)
trying to TLDR : we can listen/get
NavArgs
through
SavedStateHandle
with `LiveData`/`StateFlow`, and I was wondering if there was a similar api for `State`/`MutableState`
i

Ian Lake

05/04/2022, 3:16 PM
Args you get from Navigation should be considered a static values (they are part of the identity of what screen you're on), so using StateFlow or anything is already unnecessary - just a single get is enough
1
n

nitrog42

05/04/2022, 3:18 PM
hmmm that’s right !
17 Views