[Note]: Ignore all the variables I am just showing the the flow of using different mangers.
Here is an example of function that I am using for my FirebaseDatabaseManage. You can see a clouser is passing into the function parameter. When your firebase insert function response after async you need to call your clouser
which I named as completion
.
class FirebaseDatabaseManager {
public func insertRecipe(with recipe: RecipeModel, completion: @escaping (Bool, String) -> Void) {
SwiftSpinner.show("Loading...")
let userID = UserDefaultManager.shared.userId
database.child(FireBaseTable.recipes.rawValue).child(userID).childByAutoId().setValue(recipe.convertToDictionary!, withCompletionBlock: { error, ref in
SwiftSpinner.hide()
guard error == nil else {
completion(false, "failed to write to database")
return
}
completion(true, ref.key ?? "no key found")
})
}
}
Now look at my ViewModel class in which I am calling my FirebaseManager method. On calling of completion I am updating my @Publisher
Which you can use to update your UI.
class RecipeViewModel: ObservableObject {
@Publisher var id = 0
func createRecipe() {
FirebaseDatabaseManager.shared.insertRecipe(with: self.recipeModel) { status, id in
self.id = id
}
}
}
Hope this help your in understand your concepts.