https://kotlinlang.org logo
#coroutines
Title
# coroutines
h

hmgeorge

02/01/2019, 5:08 AM
Hello, tutorials on kotlin describe using suspendCoroutine or suspendCancelableCoroutine as the recommended way to deal with external libraries that provide a callback interface. However, most examples given seem to be for one shot results, e.g. make a network request and wait for the result. What would be the idiomatic way to handle interactions with external libraries that provide a listener interface. e.g. FileObserver on Android where we register to observe changes but we do not know when the callback will be issued. Is using Continuation<T> an acceptable method? E.g. https://gist.github.com/hmgeorge/1e5ee34265d5154e05251c1287843515 . or is using a Channel preferred?
s

streetsofboston

02/01/2019, 12:03 PM
A Continuation is like a Single or Rx. You can continue (normally or with an error) only once. If you try more than once, you'll get an error. For a continuous callback, use a Channel whose
send
or
offer
is called on each callback. Start it within a Job (e.g use launch). Be sure to de-register your callback listener when this Job finishes/cancels.
h

hmgeorge

02/01/2019, 4:51 PM
thanks for the reply .. question though .
You can continue (normally or with an error) only once.
I thought continuations can be saved and resumed upon multiple times, (for e.g in the case of scheme call/cc) . the gist i provided works without exceptions as well.
4 Views