title: Creating Kotlin coroutine Deferred object that emitts listener callback results
body: <p>I´m currently switching from RxJava to Kotlin coroutines in a project, replacing all the Single and Observable return types by coroutine aquivalents. I´m still struggling with the following construct: An interface (e.g. of a repository) offers data query access and returns a RxJava Single. The implementation creates a Single object with Single.create and emits the result with onSuccess/onError. Now what the implementation needs to do to retrieve the data is creating a listener with callbacks and registering that listener to something. The callbacks of that created listener would then call onSuccess/onError on the selfmade Single. E.g. using firebase (although my question is not firebase specific):</p>
  
  <pre><code>interface Repository {
      fun getData(query: Query): Single&lt;DataSnapshot?&gt;
  }
  
  fun getData(query: Query): Single&lt;DataSnapshot?&gt; = Single.create { emitter -&gt;
      query.addListenerForSingleValueEvent(object : ValueEventListener {
          override fun onCancelled(error: DatabaseError?) {
              emitter.onError(Exception())
          }
  
          override fun onDataChange(data: DataSnapshot?) {
              emitter.onSuccess(data)
          }
      })
  }
  </code></pre>
  
  <p>Now what I want to have instead is the interface method returning coroutine Deferred. How does the implementation have to be created so that there also can be registered a listener with callbacks, whose results then will be delivered by the Deferred? I don´t see a way with these coroutine builders like async, launch etc. doing what onSuccess/onError would do.</p>
  
  <pre><code>interface Repository {
      fun getData(query: Query): Deferred&lt;DataSnapshot?&gt;
  }
  </code></pre>