SharedFlow Consumer Sensitive in Kotlin | by Jose Braz | November, 2022

Using FileObserver Example

Unsplash. Photo by Andy Reiger on

Sometimes, we need to model a resource as a SharedFlow To consume the changes with good Kotlin support.

For example, a flow that uses all changes to a file FileObserver Or subscribes to web feeds to receive news and update UI. In all these cases, we need a way to stop/turn off this resource so as not to waste battery or network unnecessarily (mobile device users hate this).

Now imagine if it was possible to know how many flow collectors are active and when they change. subscriptionCount of MutableSharedFlow Exactly what we need!

I create a helper function to collect subscriptionCount and trigger a callback related to whether you are collecting or not.

note that onActive Runs only if it’s the first time or if onInactive has been started or completed. in another case, onInactive is called only when onActive has already been called. His tests ensure that the same event will not be called twice in a row.

Also, note that the last event’s task is canceled before an event is launched. This is a performance optimization but needs to be looked at carefully. If you need to execute some critical task that should not be cancelled, please run it in a separate (non-cancellable) coroutine context.

we can generalize listenerSubscribers The method that uses the interface, called FlowBinderTo listen to these events and do something interesting.

back to the FileObserver above. Each time no consumer is found, the method onInactive is called, and it is necessary to stop viewing the changes in the file. In the second case, when the first consumer is detected, the method onActive is called and we need to start watching file events. Let’s see the code:

For example, using a . can be done in ViewModel Like below, and it can execute some business logic with these file events:

FileObserver is just an example of what FlowBinder What can we do.

Feel free to share other use cases for this.

Leave a Comment