2

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?

sgurdag
  • 117
  • 10
  • It depends what you're trying to do. Do you expect `fetchServerRequest()` to return a Flow with different results each time you call it? That would be kind of weird since it has no parameters. If not, then there's no point in getting a new reference to the Flow. If so, then it's fine, but you need to cancel the previous coroutine each time you start a new one. – Tenfour04 Mar 22 '22 at 18:17

1 Answers1

-2

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.

Sam Chen
  • 7,597
  • 2
  • 40
  • 73
  • 5
    This answer is incorrect on both counts. There **is** a problem with the OP's code. Every time they try to refresh data, they are starting collection of another copy of the Flow without stopping previous collection, so they will have many simultaneous coroutines running and collecting parallel Flows. Also, a Job is a reference to a running coroutine, and `launch` **does** create a coroutine. (There is no Coroutine class or interface type.) If you follow the source code, `launch()` literally calls `createCoroutine()` under the hood. – Tenfour04 Mar 22 '22 at 18:19