Rx Android

Rx Android

Rx Android is a concept used in android app development to give app better performance.

Reactive Extension?is a library that follows Reactive Programming principles to compose asynchronous and event-based programs by using the observable sequence.

Rx stands for Reactive programming, In android, it can achieve by using Rx Java and kotlin.

RxAndroid?is specific to the Android platform which utilizes some classes on top of the RxJava library.

When to use Rx Android

1.There are many situations where we can use Rx Android but choose wisely

2. Rx android can be used when you want to listen to some stream.

3. The continuous data source you want to get data from.

4. Data inside data kind of API

5. You want to perform some operation or modification on data before using it.

Rx android has mainly 4 Components

  1. Observable :?Emits a stream of data or events. i.e. a class that can be used to perform some action, and publish the result.
  2. Observer : Receivers the events or data and acts upon it. i.e. a class that waits and watches the Observable and reacts whenever the Observable publishes results.
  3. S ubscriber:?It?is an adapter between both the above component, In order to get data?Observer ?to need to subscribe?Observables.
  4. Schedulers:?One of the purposes of the?Schedulers?to decide which thread to use for what purpose.

Once?Observer ?successfully subscribes to?Observables?it will get a callback in the following methods.

  • onSubscribe():?This method is invoked when the Observer is subscribed to the Observable.?(Get call only one time)
  • onNext():?This?method is called when a new item is emitted from the Observable.?(Get called whenever data is emitted)
  • onError():?This method is called when an error occurs and the emission of data is not successfully completed.?(Get call only one time)
  • onComplete():?This method is called when the Observable has successfully completed emitting all items.?(Get call only one time)

If any Observer has subscribed to Observable it will start emitting data.

Types of Observables

No alt text provided for this image

Disposable and CompositeDisposable

Disposable(Represents a disposable resource.) is an interface which is responsible for Free up the subscription or we can say which is responsible for de-link the listeners from listing the events

Let me elaborate on this Suppose I am listening something on one screen and at some point, I go to another screen so does it make sense to listen data in the previous screen obviously no so we need to dispose of the listeners or in simple word we need to unsubscribe our listeners from listening,So that unused resource can be garbage collected and we can avoid memory leak.

Disposable is having 2 methods


void dispose(); Used to dispose the subscriptio
boolean isDisposed(); Check the status        

CompositeDisposable?is a class that implements Disposable.

A disposable container that can hold onto multiple other disposables and offers O(1) add and removal complexity.        

Observable uses some?operators?for emitting data so that we can modify data according to our needs. for that, we are already having some built-in?Operators

Some important?Operators?in Rx Android

Create

This operator creates an Observable from scratch by calling observer methods programmatically. An emitter is provided through which we can call the respective interface methods when needed.


The?create()?the method does not have an option to pass values. So we have to create the list beforehand and perform operations on the list inside the?onNext()?method.

Defer

This operator does not create the?Observable?until the?Observer?subscribes. The only downside to?defer()?is that it creates a new?Observable?each time you get a new?Observer.?create()?can use the same function for each subscriber, so it’s more efficient.

Interval

This operator creates an Observable that emits a sequence of integers spaced by a particular time interval.

Just

This operator takes a list of arguments (maximum?10) and converts the items into Observable items.?just()?makes only 1 emission. For instance, If an array is passed as a parameter to the?just()?method, the array is emitted as a single item instead of individual numbers. Note that if you pass?null?to?just(), it will return an Observable that?emits?null?as an item.

Form

This operator creates an Observable from a set of items using an Iterable, which means we can pass a list or an array of items to the Observable and each item is emitted one at a time.

Difference between?Observable.from()?and?Observable.just()?— For the same inputObservable.just()?emits only once whereas?Observable.from()emits?n?times.

Range

This operator creates an Observable that emits a range of sequential integers. The function takes two arguments: the starting number and length.

Observable.range(2, 5)

Repeat

This operator creates an Observable that emits a particular item or sequence of items repeatedly. There is an option to pass the number of repetitions that can take place as well.

Timer

This operator creates an Observable that emits one particular item after a span of time that you specify.

Observable.timer(1, TimeUnit.SECONDS)

Difference between?Observable.interval()?and?Observable.timer()?—?timer()?emits just a single item after a delay whereas?interval()?operator, on the other hand, will emit items spaced out with a given interval.

If you want to modify data emitted so you can use the following Operators

Buffer

This operator periodically gathers items from an Observable into bundles and emits these bundles rather than emitting the items one at a time.

Observable.just(“A”, “B”, “C”, “D”, “E”, “F”) .buffer(2)

Will emit data in pair of 2.

Map

This operator transforms the items emitted by an Observable by applying a function to each item.?map()?the operator allows for us to modify the emitted item from the Observable and then emits the modified item.

Map?operator can be used when we fetch items from the server and need to modify it before emitting to the UI.

FlateMap

This operator transforms each item emitted by an Observable but instead of returning the modified item, it?returns the Observable itself?which can emit data again. In other words, they merge items emitted by multiple Observables and returns a single Observable. The important difference between FlatMap and other transformation operators is that the order in which the items are emitted is not maintained.

FlatMap?operator can be used when we know that the order of the items are not important.

SwitchMap

Whenever a new item is emitted by the Observable, it will unsubscribe to the Observable that was generated from the previously emitted item and begin only mirroring the current one. In other words, it returns the latest Observable and emits the items from it.

SwitchMap?is best suited for scenarios such as a feed page when pull to refresh is enabled. When the user refreshes the screen, the older feed response is ignored and only the latest request results are emitted to the UI when using a SwitchMap.

ConcatMap

This operator functions the same way as?flatMap(), the difference being in?concatMap()?the order in which items are emitted is maintained. One disadvantage of?concatMap()?is that it waits for each observable to finish all the work until the next one is processed.

Conclusion

It's good to use Rx Android in your projects but be sure about requirements and choose wisely Operators.

Because bad use of RX can lead you to end up with memory leak.

Riyazullah Syed

Android Developer at Entro Labs IT Solutions Pvt Ltd

9 个月

can u send u r email id

回复

要查看或添加评论,请登录

Aalishan Ansari的更多文章

  • Android Activity Frequently Asked Interview Questions Part-1

    Android Activity Frequently Asked Interview Questions Part-1

    1. What is the activity?/What do you know about the activity? Ans: Activity is one of the building blocks of Android…

    6 条评论
  • MVP Architecture with Example in Android

    MVP Architecture with Example in Android

    In this blog, we will take an example of a login screen in Android and cover up MVP very simply. As shown in the above…

    2 条评论
  • Activity lifecycle callbacks A →B and B →A

    Activity lifecycle callbacks A →B and B →A

    Suppose you are having one more activity called C If you kill Activity C from the task manager so onDestroy(C)…

    1 条评论
  • Fragment to Fragment Communication Using ViewModel

    Fragment to Fragment Communication Using ViewModel

    In MainActivity class MainActivity : AppCompatActivity() { private var _activityMainBinding: ActivityMainBinding?…

    2 条评论
  • S.O.L.I.D Principles (Examples in Kotlin)

    S.O.L.I.D Principles (Examples in Kotlin)

    Lots of developers do the code, but A good developer is one who takes care of the code with respect to many programming…

    1 条评论
  • Design Patterns (Very simple examples)

    Design Patterns (Very simple examples)

    In the software industry, most common problems have common solutions, and that solution follows common types of…

    1 条评论
  • References Role in Garbage Collection

    References Role in Garbage Collection

    In Java, there are four types of references differentiated by the way by which they are garbage collected. Strong…

  • Activity|LaunchMode|With Lifecycle

    Activity|LaunchMode|With Lifecycle

    Before starting development in any platform first, we should understand the ecosystem of the platform. If you are…

    2 条评论
  • OOPs Concepts (Examples in Kotlin)

    OOPs Concepts (Examples in Kotlin)

    Object-Oriented Programming in detail. The Oops concepts are the foundation when you want to create a good application…

  • Context/Application Context?

    Context/Application Context?

    Context is the bridge between components. You use it to communicate between components, instantiate components, and…

    1 条评论

社区洞察

其他会员也浏览了