kotlin 截取部分字段_RxAndroid和Kotlin(第1部分)

kotlin 截取部分字段

by Ahmed Rizwan

通过艾哈迈德·里兹万(Ahmed Rizwan)

RxAndroid和Kotlin(第1部分) (RxAndroid and Kotlin (Part 1))

When I first started using RxAndroid, I didn’t really get it. I mean, I grasped abstract concept. But I didn’t understand where I should be using it.

刚开始使用RxAndroid时 ,我并没有真正了解它。 我的意思是,我掌握了抽象概念。 但是我不知道应该在哪里使用它。

But then I went through a few examples and read a few really good articles (recommend reading list at the bottom of this article.) I just got it! And my reaction was pretty much:

但是后来我看了几个例子,读了几篇非常好的文章(本文底部的推荐阅读清单。)我就明白了! 我的React几乎是:

In short, you can use Rx almost everywhere. But you shouldn’t. You should intelligently figure out where it should go. Because in some cases, using Rx can be a 100 times more productive than normal imperative programming. And in other cases, it just isn’t necessary.

简而言之,您几乎可以在任何地方使用Rx。 但是你不应该 。 您应该明智地确定应该去哪里。 因为在某些情况下,使用Rx可以比普通命令式编程提高100倍的生产率。 而在其他情况下,则没有必要。

I’ll demonstrate a few examples in both Kotlin and Java, so that you get an idea of what Rx is, as well as a comparison of the two languages.

我将用KotlinJava演示一些示例以便您了解Rx是什么,以及两种语言的比较。

Now if you aren’t yet familiar with Kotlin, it’s an awesometacular alternative to Java, that works amazingly well on Android. And oh, it’s developed by JetBrains!

现在,如果您还不熟悉Kotlin,它是Java的绝佳替代品,可在Android上出色地运行。 哦,它是由JetBrains开发的!

P.S. There are no semicolons in Kotlin. *_*

PS:Kotlin语中没有分号。 * _ *

If you want to read more, check out:

如果您想了解更多信息,请查看:

Official Kotlin Website

Kotlin官方网站

Getting Started on Android

Android入门

Jake Wharton’s Paper on Kotlin

杰克·沃顿(Jake Wharton)关于Kotlin的论文

My Blog ;)

我的博客 ;)

Now let’s get back to Rx.

现在让我们回到Rx。

If you already have a good concept of Rx, then you can skip this topic. Otherwise, read on.

如果您已经对Rx有了一个很好的概念,则可以跳过此主题。 否则,请继续阅读。

Ok so what is Rx? Well, it’s “reactive programming.” Reactive programming is, in easy words, a programming pattern closely related to the Observer Pattern, in which, Subscribers “react” to the events emitted by these Observables.

好吧,Rx是什么? 好吧,这是“React式编程”。 用简单的话来说,React式编程是一种与观察者 模式密切相关的编程模式,在该模式中,订户对这些可观察对象发出的事件进行“React”。

Here’s a diagram:

这是一个图:

Rx is also a subset of Functional Programming. Hence often referred to as Functional Reactive Programming. As the subscribers receive data, they can apply a sequence of transformations on them, similar to what we can do with Streams in Java 8.

Rx也是函数式编程的子集。 因此通常称为功能React式编程。 订阅者接收数据时,他们可以在其上应用一系列转换 ,类似于我们在Java 8中对Streams所做的操作。

Here’s another helpful diagram:

这是另一个有用的图:

We can even merge streams into one another. It’s that flexible! So for now, just remember that there are tons of different things we can do with the data we (the subscribers) receive from observables, on the fly.

我们甚至可以将流合并在一起。 就是那么灵活! 因此,就目前而言,请记住,我们(订户)可以随时随地从观测站接收到的数据可以做很多不同的事情。

Now that the concept is somewhat clear, lets get back to RxJava.

现在这个概念已经很清楚了,让我们回到RxJava。

In Rx, the subscriber implements three methods to interact with observable:

在Rx中, 订户实现了三种与observable进行交互的方法:

  1. onNext(Data): Receives the data from the observable

    onNext(Data):从可观察对象接收数据
  2. onError(Exception): Gets called if an exception is thrown

    onError(Exception):如果引发异常,则调用
  3. onCompleted(): Gets called when the data stream ends

    onCompleted():当数据流结束时被调用

This can be compared to the Iterables in Java. The difference is that iterables are pull-based, and Rx observables are push-based. The observable pushes out data to its subscribers.

可以将其与Java中的Iterables进行比较。 区别在于,可迭代对象是基于拉的 ,而Rx可观察对象是基于推的 。 可观察者将数据推送到其订户。

Here’s the comparison table:

这是比较表:

Another thing to note is that Rx is synchronous in nature, meaning you'll have to specify if you want it to be asynchronous. You can do that by calling the observeOn and subscribeOn methods.

要注意的另一件事是Rx本质上是同步的,这意味着您必须指定是否希望它是异步的。 您可以通过调用observeOnsubscribeOn方法来实现。

So observables push out streams of data to their subscribers, and subscribers can consume those streams with the help of the methods listed above. We can understand “streams” a bit better with the help of Marble Diagrams:

因此,可观察者将数据流推送到其订户,订户可以借助上面列出的方法使用这些流 借助大理石图,我们可以更好地理解“流”:

The circles on these streams represent data objects. And the arrows represent that the data is flowing in one direction in an orderly fashion.

这些流上的圆圈代表数据对象 。 箭头表示数据在一个方向上有序地流动。

Have a look at this marble diagram:

看一下这个大理石图:

Like I mentioned before, we can transform the data (as well as streams) using operators like map, filter, and zip. The image above represents a simple mapping. So after this transformation, the subscriber to this stream will get the transformed version of the stream. Cool, right?

就像我之前提到的,我们可以使用诸如map,filter和zip之类的运算符转换数据(以及流)。 上面的图像代表一个简单的映射。 因此,在此转换之后,该流的订阅者将获得该流的转换版本。 酷吧?

You should now have a good concept of how things work in Rx, so lets get to the actual implementation.

现在,您应该对Rx中的工作方式有一个很好的了解,因此让我们开始实际的实现。

实施可观察 (Implementing Observables)

The first thing we have to do is meditate.

我们要做的第一件事是打坐。

After that, creating an observable isn’t all that difficult.

在那之后,创建一个可观察的对象并不是那么困难。

There are a number of ways we can create observables. I’ll list three here:

我们可以通过多种方法来创建可观察值 。 我将在这里列出三个:

  1. Observable.from() creates an observable from an Iterable, a Future, or an Array.

    Observable.from()从Iterable,Future或Array创建可观察对象。

//KotlinObservable.from(listOf(1, 2, 3, 4, 5))//JavaObservable.from(Arrays.asList(1, 2, 3, 4, 5));
//It will emit these numbers in order : 1 - 2 - 3 - 4 - 5 //Which should be pretty obvious I guess.

2. Observable.just() creates observable from an object or several objects:

2. Observable.just()从一个或多个对象创建可观察对象:

Observable.just("Hello World!") //this will emit "Hello World!" to all its subscribers

3. Observable.create() creates an observable from scratch by means of a function. We just implement the OnSubscribe interface, then tell the observable what it should send to its subscribers:

3. Observable.create()通过函数从头创建一个可观察对象。 我们只实现OnSubscribe接口,然后告诉观察对象它应该发送给其订阅者的内容:

//KotlinObservable.create(object : Observable.OnSubscribe<Int> {    override fun call(subscriber: Subscriber<in Int>) {        for(i in 1 .. 5)            subscriber.onNext(i)        subscriber.onCompleted()    }})

And here’s the Java version of the same code:

这是相同代码的Java版本:

//JavaObservable.create(new Observable.OnSubscribe<Integer>() {    @Override    public void call(final Subscriber<? super Integer> subscriber) {        for (int i = 1; i <= 5; i++)            subscriber.onNext(i);        subscriber.onCompleted();    }});
//Using the implementation above, we're telling the observer what //it should do when a subscriber subscribes to it. Hence the name //"onSubscribe".

The code I’ve written above is equivalent to the example I wrote for Observable.from() but as you can see, we have full control as to what should be emitted and when the stream should end. I can also send caught exceptions with the use of subscriber.onError(e).

我上面编写的代码与我为Observable.from()编写的示例等效,但是如您所见,我们完全控制应发出的内容以及何时结束流。 我还可以使用Subscriber.onError(e)发送捕获的异常。

Now we just need some subscribers.

现在我们只需要一些订户。

实施订户 (Implementing Subscribers)

For Android, to subscribe to an observable, we first tell the observable about the threads on which we plan to subscribe to and observe. RxAndroid gives us Schedulers, through which we can specify the threads.

对于Android,要订阅一个可观察对象,我们首先要告诉该可观察对象关于我们计划订阅和观察的线程的信息。 RxAndroid为我们提供了Schedulers ,通过它们我们可以指定线程。

So let’s take a simple “Hello World” observable for example. Here we’ll do the subscription on a worker thread, and the observation on the main thread:

因此,让我们以一个简单的“ Hello World”为例。 在这里,我们将在工作线程上进行预订,并对主线程进行观察:

//KotlinObservable.just("Hello World")          .subscribeOn(Schedulers.newThread())           //each subscription is going to be on a new thread.          .observeOn(AndroidSchedulers.mainThread()))           //observation on the main thread          //Now our subscriber!          .subscribe(object:Subscriber<String>(){            override fun onCompleted() {             //Completed            }            override fun onError(e: Throwable?) {             //TODO : Handle error here            }            override fun onNext(t: String?) {             Log.e("Output",t);            }           })
//Java Observable.just("Hello World")        .subscribeOn(Schedulers.newThread())        .observeOn(AndroidSchedulers.mainThread())        .subscribe(new Subscriber<String>() {            @Override            public void onCompleted() {                //Completion            }            @Override            public void onError(final Throwable e) {                //TODO : Handle error here            }            @Override            public void onNext(final String s) {                Log.e("Output",s);            }        });
//You can get more info about schedulers and threading here.

So… What does this do?

所以……这是做什么的?

When you run this code — it displays a log message:

运行此代码时-它显示一条日志消息:

Output: Hello World!

And that’s it! This is how simple “subscription” is. You can get more details about subscribe here.

就是这样! 这就是简单的“订阅”。 您可以在此处获取有关订阅的更多详细信息。

实际示例:反跳 (A Practical Example: Debounce)

So now you have an idea of how you can create some simple observables, right? So let’s implement one of my favorite RxExamples. I want to implement this:

所以现在您有了如何创建一些简单的可观察对象的想法,对吗? 因此,让我们实现我最喜欢的RxExamples之一。 我想实现这个:

In this example, I enter text into an EditText. This automatically triggers a response in which I print out the text.

在此示例中,我将文本输入EditText 。 这会自动触发一个响应,我将在其中打印出文本。

Now the response could be a call to an API. So making this API call ever time I type a character would be wasteful, since I only need a response for the last character. So I should trigger a call only when I stop typing — let’s say one second after I finish typing.

现在,响应可能是对API的调用。 因此,每次我键入一个字符时都要进行此API调用会很浪费,因为我只需要最后一个字符的响应即可。 因此,只有在我停止输入时才应该触发呼叫-假设输入完毕后一秒钟。

So how do we do this in non-reactive programming? Well, it ain’t pretty!

那么我们如何在非React式编程中做到这一点呢? 好吧,这不漂亮!

非React性反跳 (A Non-Reactive Debounce)

I use a Timer, and schedule it to call the run() method after a 1000 milliseconds of delay in the afterTextChanged() method. Oh, and don’t forget to add runOnUiThread() in there as well.

我使用一个Timer,并安排它在afterTextChanged()方法中经过1000毫秒的延迟后调用run ()方法。 哦,别忘了在那里也添加runOnUiThread()

Conceptually it’s not that difficult, but the code becomes cluttered. Even more so in Java!

从概念上讲,这并不困难,但是代码变得混乱。 在Java中更是如此!

Java version:

Java版本:

Kotlin version:

Kotlin版本:

React性解决方案 (Reactive Solution)

A Reactive solution is much more boilerplate-free. And there are only 3 steps to it.

React性解决方案几乎没有样板。 仅有3个步骤。

  1. Create an observable

    创建一个可观察的
  2. Add the Debounce operator set to a 1000 milliseconds (1 second) delay

    将Debounce运算符设置为延迟1000毫秒(1秒)
  3. Subscribe to it

    订阅它

First the Java code:

首先是Java代码:

Now the Kotlin ❤

现在是Kotlin❤

对于更少的样板,请使用RxBindings。 (For even less boilerplate, use RxBindings.)

Now for almost no boilerplate, we can use RxBindings which has many super-awesome bindings for UI widgets. And it works on both Java and Kotlin! Using bindings, the code becomes:

现在几乎没有样板,我们可以使用RxBindings 它具有许多针对UI小部件的超棒绑定。 它可以在Java和Kotlin上运行! 使用绑定,代码变为:

As you can see, there’s very little boilerplate, and the code is much more to-the-point. If I were to go back to this code in a few months, it would hardly take me a minute to figure out what’s going on. And that is priceless!

如您所见,样板非常少,而且代码更直接。 如果我要在几个月后回到这段代码,几乎不需要我花一分钟的时间来弄清楚发生了什么。 那是无价的!

Here are some awesome resources for Rx that I recommend. Do check these out!

这是我推荐的一些很棒的Rx资源。 请检查这些!

Official Rx Page

官方接收页面

Grokking RxJava Series by Dan Lew

Dan Lew的Grokking RxJava系列

Android Rx, and Kotlin : A case study

Android Rx和Kotlin:案例研究

Replace AsyncTasks with Rx

用Rx替换AsyncTasks

PhilosophicalHacker Blog on Rx

Rx上的PhilosophicalHacker博客

Implementing EventBus in Rx

在Rx中实现EventBus

RxKotlin

RxKotlin

翻译自: https://www.freecodecamp.org/news/rxandroid-and-kotlin-part-1-f0382dc26ed8/

kotlin 截取部分字段

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值