title: Kotlin: Make the function wait to return until for loop is complete
body: <p>I have a simple function that retrieves a value from Firebase Firestore. I want to return the value. How do I make the function wait until the value is retrieved, rather than immediately returning an empty value?</p>
  <p>Please Kotlin only.</p>
  <pre><code>         fun fireStoreGetter(keyVal: String): String {
              Log.d(&quot;FIRESTORE_OP&quot;, &quot;fGet running with keyVal: &quot; + keyVal)
              //logs: FIRESTORE_OP: fGet running with keyVal: exampleString
              var userId :String = &quot;&quot;
              var mFirebaseDatabaseInstances = FirebaseFirestore.getInstance()
              val user = FirebaseAuth.getInstance().currentUser
              if (user != null) {
                  userId = user.uid
                  //Log.e(TAG, &quot;User data is null&quot;)
              } else {
                  Log.d(&quot;FIRESTORE_OP&quot;, &quot;MUST AUTHENTICATE TO ACCESS FIRESTORE&quot;)
              }
              Log.d(&quot;FIRESTORE_OP&quot;, &quot;USER IN WITH UID: &quot; + userId)
              //logs FIRESTORE_OP: USER IN WITH UID: DGGiDibnldhP5z6iUyf_GQ
              val docRef2 = mFirebaseDatabaseInstances.collection(&quot;users&quot;).document(userId).collection(&quot;dBase&quot;).document(&quot;exampleDoc&quot;)
              docRef2.get()
              .addOnSuccessListener { document -&gt;
                  //for (document in result) {
                          if (document != null) {
                              //docVal is instantiated in main thread
                              docVal = document.getString(keyVal).toString()//String(keyVal)
                              Log.d(&quot;FIRESTORE_OP&quot;, &quot;DOCVAL SET: &quot; + docVal)
                              //logs: FIRESTORE_OP: DOCVAL SET: (correct value from firestore)
                          }
              }
          Log.d(&quot;FIRESTORE_OP&quot;, &quot;RETURNING fGet: &quot; + &quot;VALUE: &quot; + docVal)
          //logs: FIRESTORE_OP: RETURNING fGet: VALUE:       
          return docVal
          //returns empty
       }
  </code></pre>