Search code examples
androidkotlinrx-java2kotlin-coroutines

Why I can't use an emit function in Kotlin Flow like rxJava.Single.create?


I'm trying to rewrite interactors with rxjava chains to kotlin flow. In LocationHandlerImpl I'm using LocationService for getting my current location. In addOnSuccessListener and addOnFailureListener I'm emitting my model but having error:

emit

"Suspension function can be called only within coroutine body". Am i doing it wrong? But i can call emit outside of listeners (look below flow builder)


Solution

  • As mentioned from Prokash (here), Flows are designed to be self contained. Your location services listener is not within the scope of the Flow.

    You can however check out the callbackFlow which provides you the mechanics you are looking for to build a flow using a Callback-based API.

    Callback Flow Documentation, be aware that the callback flow is still in Experimental phase.