Home > Blockchain >  How to clear repository cache when the user logs out?
How to clear repository cache when the user logs out?

Time:03-16

I have an repository that contains an in-memory cache list inside a StateFlow. The problem is that whenever the user logs out and logs into another account, the old data from the previous user is still there.

object Repository {

    private lateinit var remoteDataSource: RemoteDataSource

    operator fun invoke(remoteDataSource: remoteDataSource) {
        this.remoteDataSource = remoteDataSource

        return this
    }

    private val myList = MutableStateFlow(listOf<myData>())

    suspend fun getData(): Flow<List<myData>> =
        withContext(Dispatchers.IO) {
            if (myList.value.isEmpty()) {
                val response = remoteDataSource.getData()
                if (response != null) {
                    myList.value = response.map { it.toMyData() }
                }
            }

            myList
        }

    suspend fun addData(newData: MyData) =
        withContext(Dispatchers.IO) {
            myList.value = myList.value.plus(newData)
            remoteDataSource.addData(myData.toMyDataRequest())
        }

}

This repository is used by multiple ViewModels. The list itself is only observed by one screen (let's call it myFragment), but other screens can add new elements to it. I've tried to clear the repository on myFragment's onDestroyView, but it clears the list whenever the user navigates away from myFragment (even when it's not a logout).

We could observe whenever the user logs out in an userRepository, but i don't know how to observe data in one repository from another repository (there's nothing like viewModelScope.launch to collect flows or something like that).

What approach can be used to solve this? And how would it clear the list?

CodePudding user response:

i don't know how to observe data in one repository from another repository

I'd argue you shouldn't in this case.

You have a use-case: Logout.

When you invoke this use-case, you should perform al the necessary operations that your app requires. In this case, you should call your repository to let it know.

suspend fun clearData() =
        withContext(Dispatchers.IO) {
            // clear your data
        }

I'd argue that you shouldn't hardcode the Dispatcher, since you'll likely test this at some point; in your tests you're going to use TestDispatcher or similar, and if you hardcode it, it will be harder to test. You write tests, right?

So now your use case..

class LogoutUseCase(repo: YourRepo) {
   operator fun invoke() { 
      repo.clearData()
      //do the logout
   }
}

That's how I would think about this. Your scope for all this is the UI that initiated the logout...

  • Related