Rxjava Custom operator (implements its own operator) __java

Source: Internet
Author: User
Tags throwable

You can implement your own observable operator, and this article shows how to do it.

If your operator is used to create a observable instead of transforming or responding to a observable, use the Create () method and do not attempt to manually implement observable. In addition, you can use the following instructions to create a custom operator.

If your operator is a separate data item for observable launch, follow the instructions below: Sequence Operators. If your operator is the entire sequence of data used to transform observable launches, follow this instruction: transformational Operators. Sequence Operators

The following example shows you how to use the lift () operator to use your custom operator (in this case, myoperator) with the standard Rxjava operators (such as OfType and map):

fooobservable = Barobservable.oftype (Integer). Map ({it*2}). Lift (new myoperator<t> ()). Map ({"Transformed by Myoperator: "+ It}";

The following section shows you the scaffold form of your operator so that it can be used correctly with lift (). Implement your operator

Define your custom operator as a public class that implements the Operator interface, like this:

public class Myoperator<t> implements operator<t> {public
  myoperator (/* Any necessary params here/*) { /
    * Add the necessary initialization code here */
  }

  @Override public
  subscriber<. Super T> Call (Final subscriber<. Super t> s) {return
    new subscriber< ;t> (s) {
      @Override public
      void oncompleted () {/
        * * * Add your own oncompleted behavior here, or simply pass the completion notice: *
        /if (! S.isunsubscribed ()) {
          s.oncompleted ();
        }
      }

      @Override the public
      void OnError (Throwable t) {/
        * * Here Add your own onError behavior, or simply pass the error notification: *
        /if (!s.isunsubscribed ()) {
          s.onerror (t);
        }
      }

      @Override public
      void OnNext (T item) {/
        * This example performs a sort operation on each item of the result, and then returns the result * *
        (!s.isunsubscribed ()) {
          Transformeditem = myoperatortransformoperation (item);
          S.onnext (Transformeditem);}}}
transform operator

The following example shows you how to use the compose () operator to get your custom operator (in this case, an operator named Mytransformer, It converts a observable of a emitted integer to a transmitting string) in conjunction with a standard Rxjava operator (such as OfType and map):

fooobservable = Barobservable.oftype (Integer). Map ({it*2}). Compose (new mytransformer<integer,string> ()). Map ( {"Transformed by Myoperator:" + it});

The following section shows you the scaffold form of your operator so that it can be used correctly with compose (). to implement your converter

Define your custom operator as a public class that implements the Transformer interface, like this:

public class Mytransformer<integer,string> implements transformer<integer,string> {public
  Mytransformer (/* Any necessary params here * *
    * * * Add the necessary initialization code here/
  }

  @Override public
  observable<st Ring> Call (observable<integer> source) {
    * 
     * * This simple example transformer apply a map operation,
     * This map operation transforms the emitted integer into a string representation of the emitted integer.
     */Return
    Source.map (new func1<integer,string> () {
      @Override public String call
      (Integer t1) {return
        string.valueof (t1);
      }
    } );
  }
}
See

"Don ' t break the Chain:use Rxjava's compose () operator" by Dan Lewother needs for considerationBefore launching any data (or notification) to the subscriber, your sequence operator may need to check its subscriber.isunsubscribed () status, and if there are no subscribers, there is no need to waste time generating data items. Please note: Your sequence operators must compound the core principles of the observable protocol:
It may call the subscriber's OnNext () method any time, but these calls must not overlap. It can only call the subscriber's oncompleted () or onError () exactly once, but not all, and the subscriber's OnNext () method cannot be invoked after this. If you can't guarantee that the operator complies with these two principles, you can add the serialize () operator to it, which forces the correct behavior to persist. Please pay attention here Issue #1962 &mdash; need to have a plan to create a test scaffold that you can use to write tests to verify that your new operator complies with the observable protocol.
Do not allow your operator to block other operations. When possible, your should compose new operators by combining existing-operators, rather-than implementing them with new CO De. Rxjava itself does this with some of it standard operators, for example: if possible, you should combine existing operators to create your new operator instead of starting from scratch to implement it. -Rxjava's own standard operators do the same, such as:
The () is defined as take (1). Single () ignoreelements () is defined as filter (Alwaysfalse ()) reduce (a) is defined as scan (a). Last () If your operator uses a function or lambda expression as a parameter, note that they may be the source of the exception, and are prepared to catch these exceptions and use OnError () to notify subscribers.
Some exceptions are considered fatal, and for them, calling OnError () is meaningless, or useless, or just a compromise of the problem. You can use the Exceptions.throwiffatal (Throwable) method to filter out these fatal exceptions and throw them back, rather than trying to launch a notification about them. In general, subscribers should be notified immediately when an error occurs, rather than attempting to launch more data first. Please note that null may be a legitimate data emitted by observable. One source of frequent errors is to test some variables and hold a non-null value as an alternative to whether or not to launch the data. A null-valued data is still a launch data item, and it cannot be equated with nothing firing anything. It can be tricky to get your operator to backpressure in the back-pressure scenario. Refer to Dávid Karnok's blog Advanced Rxjava, here's a discussion of the various factors involved and how to deal with them.

The content of this article is from: Https://github.com/mcxiaoke/RxDocs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.