Dmitry Sergienko
Dmitry Sergienko

Reputation: 125

Jetpack Compose how to show the latest values in offline mode?

I have weather application. The values comes from rest API. I would like to keep the last data values on the screen in case the user will use the app in offline mode. I use JetPack DataStore to save and get the saved values.

I subscribe to LiveData and try to save the LiveData state in JetPack DataStore. Looks the satate saved vell, but when I open App in off line mode the funcition run again and save new default values = 0.0 How to fix it?

class SaveDataStore(private val context: Context) {

// to make sure there's only one instance
companion object {
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore("temp_C")
    val TEMP_C = stringPreferencesKey("temp_C")
}

//save email into datastore
suspend fun save(name: String) {
        context.dataStore.edit { preferences ->
            preferences[TEMP_C] = name
        }
}

//get the saved email
val getTempC: Flow<String?> = context.dataStore.data
    .map { preferences ->
        preferences[TEMP_C] ?: "!!!"
    }

}

// Compose fun

// a coroutine scope
val scope = rememberCoroutineScope()
// we instantiate the saveEmail class
val dataStore = SaveDataStore(context)


val mainScreenViewModel = hiltViewModel<HomeViewModel>()
val state by mainScreenViewModel.stateMain.collectAsState()

val stateNew = state.tempC.toString()

fun initSave() {
    scope.launch {
        dataStore.save(stateNew)
    }
}
initSave()

val savedData = dataStore.getTempC.collectAsState(initial = "")

fun result(state:String, savedState:String):String {
    return if (state.toDouble() != 0.0) state 
    else savedState
}

Upvotes: 0

Views: 353

Answers (1)

Jan B&#237;na
Jan B&#237;na

Reputation: 7278

You should move the logic to your ViewModel.
Have a state in your ViewModel that will be backed up by the datastore getTempC. Then in init{} or some refresh method in the ViewModel, do the api call and only save new value to the datastore if it succeeds.

Upvotes: 0

Related Questions