title: Displaying activity indicator while loading async request in SwiftUI
body: <p>I have a basic view that displays a list that fetches data from an API. I want to implement an activity indicator while the data is being retrieved from the API. In MVC we could use a delegate and protocol and make the view controller inherit the protocol, and after the model has finished fetching the data we call the delegate to tell the view controller that the data has finished retrieving (now hide the activity indicator, etc.). How to achieve a similar thing in SwiftUI and it's MVVM style?</p>
  
  <p>I have tried implementing an activity indicator from this question, I just don't get how and when to stop it: <a href="https://stackoverflow.com/questions/56496638/activity-indicator-in-swiftui">Activity indicator in SwiftUI</a></p>
  
  <p>My SourcesViewModel (it fetches news article sources from newsapi.org)</p>
  
  <pre><code>import UIKit
  
  class SourcesViewModel: Identifiable {
  
      let id = UUID()
  
      let source: Sources
  
      init(source: Sources) {
          self.source = source
      }
  
      var name: String {
          return self.source.sourceName
      }
  
      var description: String {
          return self.source.sourceDescription
      }
  }
  </code></pre>
  
  <p>My SourcesListViewModel:</p>
  
  <pre><code>import Combine
  
  class SourcesListViewModel: ObservableObject {
  
      init() {
          fetchSources()
      }
  
      @Published var sources = [SourcesViewModel]()
      private func fetchSources() {
          NetworkManager.shared.getSourceData { (sources) in
              self.sources = sources.map(SourcesViewModel.init)
          }
      }
  }
  </code></pre>
  
  <p>Lastly, my SourcesView:</p>
  
  <pre><code>import SwiftUI
  
  struct SourcesView: View {
      @ObservedObject var model = SourcesListViewModel()
  
      var body: some View {
          ActivityIndicatorView(isShowing: .constant(true)) {
              NavigationView {
                  List(self.model.sources) { source in
                      VStack(alignment: .center) {
                          Text(source.name)
  
                          Text(source.description)
                              .foregroundColor(.secondary)
                              .lineLimit(3)
                      }
                      .navigationBarTitle(Text("Sources"), displayMode: .inline)
                  }
              }
          }
      }
  }
  
  
  struct ContentView_Previews: PreviewProvider {
      static var previews: some View {
          SourcesView()
      }
  }
  </code></pre>
  
  <p>The result:</p>
  
  <p><a href="https://i.stack.imgur.com/sgkQX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sgkQX.png" alt="how to stop loading"></a></p>