lundi 28 juin 2021

How to get coroutine scope in lower level manager class

I have a data manager class in one of my libraries. Until now it was working with executors and had its own executor. Now the class is being converted to coroutines.

The problem arises when the manager has to initialize the data asynchronously as in below example. In order to execute suspend function, the call to suspendedInit has to be wrapped in launch. The issue here is that the manager has no its own coroutine scope.

There are some that I am looking at and don't like:

  1. passing coroutine scope into DataManager constructor and using it. The issue with that the the user of DataManager does not yet support coroutines and hence has no own scope.
  2. DataManager implementing CoroutineScope and creating its own scope. This is discouraged as documented by CoroutineScope documentation.

What is the recommended solution to this problem?

    class DataManager {
        init {
            suspendedInit()
        }
        
        private suspend fun suspendedInit() = withContext(Dispatchers.IO) {
            /* some long asynchronous operations here */
        }
    }

Aucun commentaire:

Enregistrer un commentaire