Hi everyone! I want to do async for API request in a suspend function like below: ```override suspen...
f
Hi everyone! I want to do async for API request in a suspend function like below:
Copy code
override suspend fun getMovieDetails(movieId: Int): LiveData<MovieEntity> {
        GlobalScope.launch {
            async {
                try {
                    val movieData = mService.getMovieDetails(movieId)
                    mCache.updateMovie(movieData)
                    Rose.error("done") // *(2)*
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

        }

        Rose.error("run first") // *(1)*
        return Transformations.map(mCache.getMovie(movieId)) {
            return@map MovieEntity(....)
        }
    }
I want (1) run first, then run (2). I managed to do that with GlobalScope, but GlobalScope is highly discouraged (I read this here https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html) I also searched on the internet and in this channel with keyword: async suspend function. But haven’t found any answer. Is there any other way to do that? Could anyone help me on this? Thank you so much.
z
How do you actually want your function to behave? The signature you have right now sends mixed messages: it's a suspend function, which suggests that it does some long-running work and suspends the caller until it's done, but it also returns a stream type (LiveData) which suggests that it just kicks off the long-running task asynchronously and returns immediately.
❤️ 1
f
Hi zachklipp, thank you for your reply. 😊 in this function, I want to return immediately the movie data in Room database (movie data already have in the database) then I want to get the movie from API which is using suspend to get other values for movie object then update to Room database (Room return LiveData object) Because Room database return LiveData so when the API request is done and update to database, the movie data will be reflected to the return value of the whole function (LiveData<MovieEntity> )
did I use coroutines in a correct way? 😅
l
I suggest you read about structured concurrency, or watch this great talk about it:

https://www.youtube.com/watch?v=Mj5P47F6nJg

❤️ 1
f
thank Louis CAD.
z
Sound like your function doesn't need to be a suspend function then. You can launch a coroutine to do your network/DB work using the
liveData
coroutine builder. https://developer.android.com/topic/libraries/architecture/coroutines#livedata
💯 1
❤️ 1
🎉 1
f
Thank you so much zachklipp. I’ll try.
yes, liveData coroutine builder works in my case. thank you so much zahklipp 😄