diff LazyBearWatchOS Extension/Views/Home/HomeView.swift @ 452:bb69f9d1d20f

Implement HomeView in WatchOS
author Dennis Concepción Martín <dennisconcepcionmartin@gmail.com>
date Sat, 26 Jun 2021 18:45:31 +0200
parents 8621ba6fd457
children 37c13ebda381
line wrap: on
line diff
--- a/LazyBearWatchOS Extension/Views/Home/HomeView.swift	Sat Jun 26 17:04:29 2021 +0200
+++ b/LazyBearWatchOS Extension/Views/Home/HomeView.swift	Sat Jun 26 18:45:31 2021 +0200
@@ -9,12 +9,51 @@
 import CoreData
 
 struct HomeView: View {
+    @ObservedObject var profile = Profile()
+
     @FetchRequest(entity: WatchlistCompany.entity(), sortDescriptors: [])
     var watchlistCompanies: FetchedResults<WatchlistCompany>
     
+    @State private var timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect()  /// Set recurrent price request
+    
     var body: some View {
-        VStack {
+        if profile.showView {
+            NavigationView {
+                ScrollView {
+                    VStack {
+                        if let companies = profile.data.quotes {
+                            ForEach(companies, id: \.self) { company in
+                                CompanyRow(company: company)
+                            }
+                        }
+                    }
+                }
+                .navigationTitle("Lazybear")
+                .onAppear { self.timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect() }  /// Start timer
+                .onDisappear { self.timer.upstream.connect().cancel() }  /// Stop timer
+                .onReceive(timer) { _ in prepareUrl(.streaming) }
+            }
+        } else {
+            ProgressView()
+                .onAppear { prepareUrl(.initial) }
+        }
+    }
+    
+    /*
+     Get symbols in watchlists (Core Data) -> Prepare url -> Request
+     */
+    private func prepareUrl(_ requestType: RequestType) {
+        let symbols = Set(watchlistCompanies.map { $0.symbol })
+        let symbolsString = symbols.joined(separator:",")
+        
+        switch requestType {
+        case .initial:
+            let url = "https://api.lazybear.app/profile/type=initial/symbols=\(symbolsString)"
+            profile.request(url, .initial)
             
+        default:
+            let url = "https://api.lazybear.app/profile/type=streaming/symbols=\(symbolsString)"
+            profile.request(url, .streaming)
         }
     }
 }