简体   繁体   中英

How to call suspend function on init?

I'm a bit lost here, I dont quite get how suspend functions work yet so any tips or fix for this one?

init:

init {
    val settings = FirebaseFirestoreSettings.Builder()
        .setCacheSizeBytes(FirebaseFirestoreSettings.CACHE_SIZE_UNLIMITED)
        .build()
    db.firestoreSettings = settings
    credentials = getCredentials() // Throws 'Suspend function 'getCredentials' should be called only from a coroutine or another suspend function'
}

Suspend function:

// ... this function is defined for my repository interface
override suspend fun getCredentials(): Resource<CredentialsDTO> {
        return try {
            if(this::credentials.isInitialized)
                Resource.Success(credentials)
            else {
                val _credentials = api.getCredentials()
                credentials = _credentials 
            }
        } catch(e: Exception) {
            e.printStackTrace()
            Resource.Error("Error thrown: ${e.localizedMessage}")
        }
    }

You haven't told us where this init block is located, but the solution is as it says: you have to call your suspend function from a coroutine.

So what you're really asking is how you can launch a coroutine. However, this depends on where you're init ing. The suggested modern architecture is to use a ViewModel , within which you can launch your coroutine with ViewModelScope.launch . Within the launch you're free to use your suspend functions. The ViewModel , you then use in whatever view you need.

See these for details:

This architecture will introduce some complexity at first as you learn, but is much more robust in the long term.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM