Reputation: 28541
I am a little new to RxJava 2. I am fine with subscribing to observables which are given to me from 3rd party libraries, or created from ranges/lists.
Now I would like to provide my own RxJava 2 flowables. Here is some context:
I have an application which needs to discover bluetooth devices. Some service is providing to me the scan records when they are detected (a device sends an update about its status, the RSSI, etc.).
Inside a DeviceRegistry, I maintain a list of devices (mac address, average RSSI, etc.) and I would like to observe from outside my DeviceRegistry when devices are added (new MAC address detected) or removed (device turned off).
I guess I should offer something like that:
class DeviceRegistry {
// All devices currently active
val devices: MutableMap<String, Device>
// Gives a way to subscribe to newly detected devices (to update the UI for instance)
fun newlyDetectedDevices(): Flowable<Device>
// Gives a way to subscribe to devices which get turned off (to update the UI for instance)
fun newlyDetectedDevices(): Flowable<Device>
fun onNewScanRecord(scanRecord) {
// Check if the device is new, if it is, emit something on the
// newlyDetectedDevices flowable
}
}
I cannot understand how to create the flowable, from what. And then also how to emit a new event on it so that the subscriber gets an event there.
Upvotes: 1
Views: 334
Reputation: 2232
I don't think your case is kinda fit Flowable
usage. Check out differences between Observable and Flowable here. According to official docs, you should use Flowable
, when:
Dealing with 10k+ of elements that are generated in some fashion somewhere and thus the chain can tell the source to limit the amount it generates.
Reading (parsing) files from disk is inherently blocking and pull-based which works well with backpressure as you control, for example, how many lines you read from this for a specified request amount).
Reading from a database through JDBC is also blocking and pull-based and is controlled by you by calling ResultSet.next() for likely each downstream request.
Network (Streaming) IO where either the network helps or the protocol used supports requesting some logical amount.
Many blocking and/or pull-based data sources which may eventually get a non-blocking reactive API/driver in the future.
In your case it's better to use Observable
instead of Flowable
. Btw you could easily create them from Subject
s. Check them out here.
Upvotes: 2