Home > Software design >  Kotlin wait for function to finish then complete code
Kotlin wait for function to finish then complete code

Time:11-07

In my code, I have 2 functions that update global variables. When I call them (On top of onCreate)

Like this:

override fun onCreate(savedInstanceState: Bundle?) {
    userManager = UserManager(this) 
        observeEmail()
        observePassword()

Code continues, I want to wait for these 2 functions to finish then to continue my code how can I do that?

As you can see first is printed message from onCreate, then from the function which is before print in onCreate

prints

code

CodePudding user response:

It looks to me like the second param in that observe() method is a callback.

My suggestion is this:

Way way up at the very top of the class, create a class-global variable called callBack like this:

callBack:(()->Unit)?=null

Then, inside of your onCreate() push everything that you want to happen after observeEmail into one massive routine and let callBack take the value of that routine. Like this:

callBack={doEverything()
doMore()
doOtherStuff()
}

Now go back inside that second param of .observe(), you know that place where you printed the email hint. And under that print line, add this:

callBack?.invoke()

Now everything will wait until observe() returns a result.

  • Related