Home > Back-end >  How to create a coroutine scope tied to a loggedin user?
How to create a coroutine scope tied to a loggedin user?

Time:11-08

Is there a way to create a CoroutineScope that is tied to the loggedIn user?

Basically, the idea is to create a coroutine scope, which I can cancel when the user logouts so that all the jobs being done on that scope gets cancelled.

My idea is to create a singleton class that holds a map between the userId and coroutineScope then inject the class wherever I need. Then I would observe the loggedInUser and cancel the scope that doesn't belong to the loggedInUser and then delete the scope.

Is this a good way or is there a more elegant way to achieve this?

CodePudding user response:

Hello if you want to store user data like lists, object etc while user is logged in then best way to go is data store. It's an upgrade to shared preferences which was previously used.

In data store you can observe data changes as it is live data and we can collect it in activity or viewModel scope.

This also works great because its lifecycle aware so you dont have to worry about cancelling it manually as it get resume on screen resume and pause when it goes in background or in back stack.

Here is a link learn more

Call api as follow

lifecycleScope.launch {
        dataStoreGetUserData().firstOrNull {
        
            callApi()

            true
        }
    }

this way data from data store is only obtained one time and will not be called everytime data changes

CodePudding user response:

I recommend to rethink your design. You don't want to store multiple scopes that are tied to some specific IDs since it will force you to do extra work like cancelling and disposing scopes that are not used or refer to another ID.

Usually, coroutines and their scopes do not depend on authentication and authorization states. You better control these states on the backend or in your business logic layer if you don't have the backend.

For example, you perform the authentication and if it fails or is not performed at all you don't provide the user with any logic/functions that requires being logged in. Otherwise, if it is performed, you pass the token/id/etc. to the following API calls, that will provide you with data that is relevant for current user.

You don't want to implement switching between coroutines that is dependent on the current user. Concurrency in your application should be structured and not very complicated. Availability of data or functionality should not depend on some coroutine scope.

  • Related