click listener in Kotlin coroutines using flow replacing RxJava

Viewed 1496

I am currently using rxjava, rx binding for button click events, I want to change that to use kotlin coroutines Flow.

how can I convert this bellow code to use Flow please

   @Override
    public Observable<Void> getStartFuellingObservable() {
        return RxView.clicks(dataViewHolder.btnStartFuelling);
    }

Thanks R

2 Answers

You can build a simple Kotlin Extension Function like the following:

fun View.clicks(): Flow<Unit> = callbackFlow {
    val listener = View.OnClickListener {
        offer(Unit)
    }
    setOnClickListener(listener)
    awaitClose { setOnClickListener(null) }
}

This article is the source

It contains more info on how to have a similar API to RxJava and it's UI bindings. I think you could benefit from a read there

Related