Hi guys! I have one peculiar problem which I am no...
# android
n
Hi guys! I have one peculiar problem which I am not sure how to handle. The issue is the following, I’ve defined a value class (lets call it Query which wraps a String primitive type). I am using DataStore preferences in which I store/retrieve the string value by wrapping/unwrapping the value to Query value class accordingly. The issue I am receiving is when I subscribe to the Flow object I get
java.lang.ClassCastException: java.lang.String cannot be cast to Query
and I am completely puzzled to why is that? I get that value classes are “deconstructed” to the primitive type in runtime, but why am I then allowed to use them like this then? Thanks!
Copy code
interface LocalDataSource {
    /**
     * Returns [Flow] object containing [Query] objects.
     */
    val queryFlow: Flow<Query>

    /**
     * Sets provided query inside the persistence solution.
     */
    suspend fun setQuery(query: Query)
}


class LocalDataStoreImpl(
    private val dataStore: DataStore<Preferences>,
) : SearchLocalDataSource {

    override val queryFlow: Flow<Query> =
        dataStore.data.map { preferences ->
            val query = preferences[QUERY_PREFERENCES_KEY] ?: ""
            Query(value = query)
        }

    override suspend fun setQuery(query: Query) {
        dataStore.edit { preferences -> preferences[QUERY_PREFERENCES_KEY] = query.value }
    }

    companion object {
        val QUERY_PREFERENCES_KEY = stringPreferencesKey("query-key")
    }
}
Where
queryFlow.firstOrNull()
or any other terminal operator crashes with above given exception.
r
Nothing in your sample is incorrect. I have to assume there’s something happening somewhere else in your code to cause the exception. Unless the stacktrace points to somewhere in those lines, that’d be my guess.