Search code examples
swiftswiftuiswift3realm

Execute call after another is completed on .onAppear{} swiftui


I have a condition inside the onAppear on my swiftui View

I want to execute the if condition after my firstCall() ends

My onAppear:

 .onAppear{
        
        firstCall()
        
        
        if mybool{ // I want this to be executed just after the firstCall() is completed
            value = repo.secondCall(int: self.initialValue)
        }
        
    }

The firstCall method that I want to end before the if condition to be executed

func firstCall(){
        
         Task{
            do{
                try await repo.firstCall().watch(block: {myView in
                    
                    self.initialValue = myView
                    
                    
                })
            }catch{
                print("error")
            }
        }
    }

I need this because I need to have a value for my self.initialValue before executing the if statement.

Also, the second call will be executed rarely, so what is the best performance way of doing this on swiftui, I am new to swift.

My repo.firstCall()

fun firstCall(): CommonFlow<User?> {
        return realm.query<User>("_id = $0", ObjectId.from(userId)).asFlow().map {
            it.list.firstOrNull()
        }.asCommonFlow()
    }

Solution

  • Change first call to a proper async await format

    func firstCall() async {
            do{
                try await repo.firstCall().watch(block: {myView in
                    
                    self.initialValue = myView
                    
                    
                })
            }catch{
                print(error)
            }
        
    }
    

    Then use .task

    .onAppear{
        Task{
        await firstCall()
        
        if mybool{ // I want this to be executed just after the firstCall() is completed
            value = repo.secondCall(int: self.initialValue)
        }
        }
    }