https://kotlinlang.org logo
t

Tiago Nunes

02/07/2021, 4:36 PM
Hi everyone, imagining this senario: -> I have a table in Room Database called "UserApplicationPreferences", where I keep configuration options for each user, and a loggedIn boolean; -> When a user enters the App, a query will be executed to find out if there is any UserApplicationPreferences with the flag loggedIn. -> If (or when) there is a loggedIn user, I want the corresponding UserApplicationPreferences instance to be synchronously available, everywhere in the app. -> Whenever the user changes their preferences, the saved instance should change (automatically, preferably). I was thinking the saved instance could be just the Flow returned in the Dao, but then to get its value I need to call collect() which is asynchronous (makes sense). Is there some way to like always be collecting from the flow and updating the instance (which will be in the Repository) or something like that? My goal is to: -> Have synchronous access to the UserApplicationPreferences (as I would when using SharedPreferences) -> Minimize queries to database (in-memory caching the up-to-date UserApplicationPreferences instead of running the query to get the up-to-date UserApplicationPreferences each time) This is working as I intended. There is no way this is good practice, right?...
Copy code
@Singleton
class UserApplicationPreferencesRepository @Inject constructor(
    private val dao: UserApplicationPreferencesDao,
){
    var loggedInUserPreferences: UserApplicationPreferences? = null
        private set

    init {
        CoroutineScope(SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>).launch {
            dao.getLoggedInFlow().collect {
                loggedInUserPreferences = it
            }
        }
    }
}
m

Mark

02/08/2021, 4:25 AM
t

Tiago Nunes

02/08/2021, 11:48 AM
So it's okay to do what I did, except the coroutine scope should be a single injected application-level coroutine scope?