• Rx Observable and a Developer (Me) [Android RxJava2] (What the hell is this) Part5
  • Hafiz Waleed Hussain
  • The Nuggets translation Project
  • Translator: Yang Yingfeng, dragon Rider general
  • Proofreader: Phoenix, JerryMissTom

A conversation between the developer (me) and the Rx Observable class (what the hell is this?) The fifth part

It’s a new day and it’s time to learn something new to make it cool.

Hello everyone, I hope you are all doing well. This is the fifth article in our RxJava2 Android series [part1, part2, part3, part4]. In this article, we’ll continue our exploration of Rx Java Android.

Motivation:

The motivation is the same one I shared with you in part1. Now let’s put together what we have learned in the previous four chapters.

Introduction:

One day when I was learning Rx Java Android, I had a friendly conversation with an Observable of Rx Java. The good news is that observables are kind, and I’m blown away. I always thought Rx Java was a screw-up. He/she doesn’t want to be friends with developers and is always giving them the slip. But after talking to the Observable, I was pleasantly surprised to find that I was wrong.

Me: Hello, Observable, have you eaten?

Observable: Hafiz Waleed Hussain, I ate.

Me: Why is your learning curve so steep? Why are you giving developers a hard time? You’re going to lose your friends.

Observable: Haha, you’re right. I really want to make a lot of friends, but I have some good friends now. They discuss me and introduce me and my ability on different forums. And these guys are really good, they spend a lot of time with me. Only faith can move mountains. But the problem is, a lot of people who try to flirt with me are more interested than interested. They follow me for a while and then they go on Twitter and Facebook and forget about me. So how can someone who isn’t sincere to me expect me to make friends with them?

Me: Well, what should I do if I want to make friends with you?

Observable: Focus on me long enough and you’ll see how sincere I am.

Me: Well, to be honest I’m not good at paying attention, but I’m good at ignoring my surroundings. Is that ok?

Observable: Sure, I’ll be your good friend as long as you and I can keep nothing else when we’re together.

Me: Wow, I have a feeling I’m going to make friends with you.

Observable: Sure, anyone can call me a good friend.

Me: Now I have some questions, can you ask?

Observable: Sure, you can ask thousands of questions. I will give you the answer, but it is important that you take your time to think and absorb it.

Me: I will. How do I convert data to an Observable in Rx Java 2 Android?

Observable: The answer to this question is very, very long. If you look at my (Rx Java 2 Observable) source code, you’ll see that I have 12, 904 lines of code. Note: in RxJava version 2.0.9. The Observable class has been successfully expanded to 13,728 lines.)

I also have several friends on my team who can return Observable objects, such as Map and filter, according to the needs of developers. But now I’m going to tell you a few things you can do to turn anything into an Observable. I’m sorry it’s going to be long, but it’s not going to be boring. I’ll show you not only how these methods create Observables, but also how to refactor the code at hand.

1 just()

With this method, you can convert any object into an Observable that is generic.

String data= "Hello World";
    Observable.just(data).subscribe(s -> System.out.println(s));
Output:
    Hello WorldCopy the code

If you have more than one data, you can call the just method as follows:

String data= "Hello World";
Integer i= 4500;
Boolean b= true;
    Observable.just(data,i,b).subscribe(s -> System.out.println(s));
Output:
    Hello World
    4500
    trueCopy the code

The API accepts up to 10 data as parameters.

,2,3,4,5,6,7,8,9,10 observables. Just (1). The subscribe (s - > System. Out. Print (s + "")); Output: 1 2 3 4 5 6 7 8 9 10Copy the code

Sample code :(not a good example, just a hint on how to use it in your own code)

public static void main(String[] args) { String username= "username"; String password= "password"; System.out.println(validate(username, password)); } private static boolean validate(String username, String password) { boolean isUsernameValid= username! =null && ! username.isEmpty() && username.length() > 3; boolean isPassword= password! =null && ! password.isEmpty() && password.length() > 3; return isUsernameValid && isPassword; }Copy the code

Observable class for refactoring:

private static boolean isValid= true; private static boolean validate(String username, String password) { Observable.just(username, password).subscribe(s -> { if (! (s ! = null && ! s.isEmpty() && s.length() > 3)) throw new RuntimeException(); }, throwable -> isValid= false); return isValid; }Copy the code

2 the from… :

I have a bunch of apis for converting complex data structures into Observables, such as the following methods that start with the keyword from:

I think the API’s name makes sense, so no more explanation is needed. But I’ll give you some examples so you can use them more comfortably in your own code.

Although fromCallable, fromPublisher, and fromFuture are also ways to start from. But they are very different from each other. Especially fromCallable and fromPublisher.)

public static void main(String[] args) { List<Tasks> tasks= Arrays.asList(new Tasks(1,"description"), new Tasks(2,"description"),new Tasks(4,"description"), new Tasks(3,"description"),new Tasks(5,"description")); Observable.fromIterable(tasks) .forEach(task -> System.out.println(task.toString())); } private static class Tasks { int id; String description; public Tasks(int id, String description) {this.id= id; this.description = description; } @Override public String toString() {return "Tasks{" + "id=" + id + ", description='" + description + '\'' + '}'; }}}Copy the code

Transform from an array to an Observable

Public static void main(String[] args) {Integer[] values= {1,2,3,4,5}; Observable.fromArray(values) .subscribe(v-> System.out.print(v+" ")); }Copy the code

Two examples will suffice, and you can try the others yourself later.

3 the create () :

You can force anything into an Observable. The API is too powerful, so I recommend looking for other solutions before using it. About 99% of the time, you can use another API to solve the problem. But if you can’t find it, you can use it.

Note: RxJava 2’s create is still at the RxJava 1 stage. RxJava 1.x does not recommend the create method. RxJava 2’s Create method is recommended. Not 99 percent of cases can be replaced. The create method of RxJava 1.x is now the unsafeCreate of RxJava 2.x, and RxJava 1.2.9 has added a new secure create overload method.

public static void main(String[] args) { final int a= 3, b = 5, c = 9; Observable me= Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(ObservableEmitter<Integer> observableEmitter) throws Exception { observableEmitter.onNext(a); observableEmitter.onNext(b); observableEmitter.onNext(c); observableEmitter.onComplete(); }}); me.subscribe(i-> System.out.println(i)); }Copy the code

4 the range () :

This is like a for loop, as shown in the code below.

Public static void main(String[] args) {observable.range (1,10).subscribe(I -> system.out.print (I +" ")); } Output: 1 2 3 4 5 6 7 8 9 10Copy the code

Here’s another example:

public static void main(String[] args) {

List<String> names= Arrays.asList("Hafiz", "Waleed", "Hussain", "Steve");
for (int i= 0; i < names.size(); i++) {
if(i%2== 0)continue;
        System.out.println(names.get(i));
    }

    Observable.range(0, names.size())
.filter(index->index%2==1)
            .subscribe(index -> System.out.println(names.get(index)));
}Copy the code

5 the interval () :

This API is awesome. I’m implementing the same requirement in two ways, so you can compare. The first is implemented using Java threads, and the other is implemented using the interval() API, both of which yield the same result.

Note: Interval () operates on Scheduler.computation() by default.

public static void main(String[] args) { new Thread(() -> { try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } greeting(); }).start(); Observable.interval(0,1000, timeunit.milliseconds). Subscribe (aLong -> greeting()); } public static void greeting(){ System.out.println("Hello"); }Copy the code

6 the timer () :

Another good API. In a program if I want to call a method after a second, I can use timer, as shown below:

public static void main(String[] args) throws InterruptedException {
    Observable.timer(1, TimeUnit.SECONDS)
            .subscribe(aLong -> greeting());
    Thread.sleep(2000);
}

public static void greeting(){
    System.out.println("Hello");
}Copy the code

7 the empty () :

This API is useful, especially when there is fake data. The Observable created by this API registers an Observer that only calls the complete method. For example, if I’m sent fake data during the test run, I’ll call the real data in production.

public static void main(String[] args) throws InterruptedException {
    hey(false).subscribe(o -> System.out.println(o));
}

private static Observable hey(boolean isMock) {
return isMock ? Observable.empty(): Observable.just(1, 2, 3, 4);
}Copy the code

8 the defer () :

This API can be useful in many situations. Let me illustrate with the following example:

public static void main(String[] args) throws InterruptedException { Employee employee= new Employee(); employee.name= "Hafiz"; employee.age= 27; Observable observable= employee.getObservable(); employee.age= 28; observable.subscribe(s-> System.out.println(s)); } private static class Employee{ String name; int age; Observable getObservable(){ return Observable.just(name, age); }}Copy the code

What does the above code output? If you answered age = 28, you’re wrong. Almost all methods that create an Observable record available values at creation time. Just like that data actually outputs age = 27, because the age value was 27 when I created the Observable, and the Observable class was already created when I changed it to 28. So how do you solve this problem? Yes, this is where the API defer comes in. It’s so useful! When you use defer, you only create an Observable when you register. Using this API, I can get the values I want.

Observable getObservable(){
  //return Observable.just(name, age);
  return Observable.defer(()-> Observable.just(name, age));
}Copy the code

So our age output is 28.

Note: In the creation method of an Observable, it is not as written in the original article. “Basically, all methods that create an Observable record available values when they are created.” I just have the just from method. Create, fromCallable, etc., are called after subscribe. In this example, you can use fromCallable instead of defer.)

9 the error () :

A way to pop up an error message. I’ll share them with you when we discuss the Observer class and its methods.

10 never () :

The API creates an Observable that does not contain generics.

Observable. Never Gets an Observable, but the registered Observer does not call onNext, onCompleted, or even onError.

Me: Wow. Thank you, Observable. Thank you for your patient and detailed answer, which I will write down in my cheat book. So, can you turn functions into Observables as well?

Observable class: Of course, look at the code below.

Public static void main(String[] args) throws InterruptedException {system.out.println (scale(10,4)); Observables. Just (scale (10, 4)). The subscribe (value - > System. Out. The println (value)); } private static float scale(int width, int height){ return width/height*.3f; }Copy the code

Me: Wow, you are really strong. Now I want to ask you a question about operators such as map and filter. But if there’s anything ELSE I haven’t asked about Observable creation due to lack of knowledge, tell me more.

Observable: There’s a lot more. I’ll introduce two types of Observables here. One is called a Cold Observable, and the second one is a Hot Observable. In the…

Conclusion:

Hello, everyone This conversation is very, very long, and I need to stop there. Otherwise, this article will look like a big book. It may look good, but it misses the point. I hope we can learn it step by step. So I’m going to pause my conversation and continue in the next post. You can try to implement these methods yourself and, if possible, apply and refactor them in real projects. Finally, I want to say thank you Observable for giving me so much of his/her time.

Have a great weekend and see you later


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. Android, iOS, React, front end, back end, product, design, etc. Keep an eye on the Nuggets Translation project for more quality translations.