I have an interaction with a third party library t...
# coroutines
c
I have an interaction with a third party library that I'm trying to bridge by using flows. Basically I have callback and I'm trying to turn it into a flowable by creating a sharedFlow.
Copy code
fun startCameraPreview(): SharedFlow<Frame> {
  val events = MutableSharedFlow<PreviewFrame>()
  
  cameraClient.addPreviewDataCallBack(
      object : IPreviewDataCallBack {
        override fun onPreviewData(...) {
          scope.launch { events.emit(PreviewFrame(data, width, height)) }
        }
      })

  return events.asSharedFlow()
}
This seems to work and I thought I wanted to treat this as a hot flow, but now I think a cold flow would work fine. Is there anything bad about having this setup this way? My biggest issue that I'm trying to prevent is for this flow to never be cleaned up I initially didn't go with a callbackFlow because (from my limited time with them) they seem to be suited for cases where there's a terminal callback event where you can "shutdown" the flow. I don't see such an event from this 3rd party lib.
j
You should probably separate concerns here. You could wrap this API using a cold
callbackFlow { ... }
that unregisters the callback on completion/cancellation, and then you can use
shareIn
if you want to share this flow between consumers.
c
Hm. How would I do "unregisters the callback on completion/cancellation"
j
Since there is
addPreviewDataCallback
I was assuming there is also the "remove" equivalent?
If that's the case you can use the
awaitClose { ... }
function in
callbackFlow
to do that
c
Okay. So convert this to a callbackFlow and implement addPreviewDataCallback and removePreviewDataCallback. Makes sense to me. Thanks for the extra set of eyes on this @Joffrey!