Is it correct to call viewModelscope.launch() method on every request?

Viewed 842

i have code like this:

class MyViewModel: ViewModel() {

    val myRepository = ExampleRepository()

    init {
        fetchServerRequest()
    }

    fun reload() {
        fetchServerRequest()
    }

    private fun fetchServerRequest() {
        viewModelScope.launch {
            myRepository.fetchServerRequest() //repository returns Flow<String>
                .collect {
                    //handle result
                }
        }
    }
}

Repository returns cold Flow. Is it correct to create new coroutine c every time when i call this method?

Or coroutine will be finished when code in collect will finished?

1 Answers

What you are doing is fine, viewModelScope.launch() isn't creating a new Coroutine, it creates a new Job, you can see the return type if you put the mouse on the launch().

Or coroutine will be finished when code in collect will finished?

You can check out my another post here.

Related