Created
October 24, 2024 22:40
-
-
Save kartikarora/9924002dd6c71441554bf52340fb14b5 to your computer and use it in GitHub Desktop.
Activity 7 Step 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Singleton | |
class DataRepository @Inject constructor( | |
@ApplicationContext private val context: Context | |
) { | |
... | |
companion object { | |
private val GENERATED_TOPICS_KEY = stringPreferencesKey("generatedTopics") | |
private const val TOPICS_DATASTORE = "topics_datastore" | |
private const val SPLITTING_DELIMITER = "::" | |
} | |
private val Context.preferenceDataStore: DataStore<Preferences> by preferencesDataStore(name = TOPICS_DATASTORE) | |
fun hasGeneratedTopics(): Flow<Boolean> { | |
return context.preferenceDataStore.data.map { preferences -> | |
preferences.contains(GENERATED_TOPICS_KEY) | |
} | |
} | |
fun getGeneratedTopics(): Flow<List<Topic>> { | |
return context.preferenceDataStore.data.map { preferences -> | |
preferences[GENERATED_TOPICS_KEY]?.split(SPLITTING_DELIMITER)?.map { | |
Topic( | |
name = it.trim(), | |
isGenerative = true, | |
quotes = emptyList() | |
) | |
} ?: emptyList() | |
} | |
} | |
suspend fun saveGeneratedTopics(topic: List<Topic>) { | |
context.preferenceDataStore.edit { preferences -> | |
preferences[GENERATED_TOPICS_KEY] = topic.joinToString(SPLITTING_DELIMITER) { it.name } | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@HiltViewModel | |
class MainViewModel @Inject constructor( | |
... | |
init { | |
viewModelScope.launch { | |
if (!dataRepository.hasGeneratedTopics().first()) { | |
generateTopics() | |
} else { | |
dataRepository.getGeneratedTopics().collect { | |
showLoading.emit(false) | |
_generatedTopics.emit(it) | |
} | |
} | |
} | |
} | |
private fun generateTopics() { | |
viewModelScope.launch(Dispatchers.IO) { | |
... | |
dataRepository.saveGeneratedTopics(newTopics) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment