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?
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.