RxJava2学习之五:Map操作符

Map 操作符是对序列的每一项都应用一个函数来变换Observable发射的数据序列。

Map 操作符对原始Observable发射的每一项数据应用一个你选择的函数,执行变换操作,然后返回一个发射这些结果的Observable。

Integer转换为String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//Integer转换为String
Observable<Integer> observable = Observable.just(1);

Observable<String> map = observable.map(new Function<Integer, String>() {
@Override
public String apply(Integer integer) throws Exception {
return integer + ": appblog.cn";
}
});

//订阅参数:Integer
observable.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
Log.i(TAG, "accept: " + integer);
}
});

//订阅参数:String
map.subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
Log.i(TAG, "accept: " + s);
}
});

Integer转换为User对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//Integer转换为User
Observable.just(1).map(new Function<Integer, User>() {
@Override
public User apply(Integer integer) throws Exception {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_ADDRESS)
.addConverterFactory(GsonConverterFactory.create())
.build();

api = retrofit.create(Api.class);
User user = api.getUserInfoWithPath(1).execute().body();
return user;
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<User>() {
@Override
public void accept(User user) throws Exception {
Toast.makeText(MainActivity.this, user.getUsername(), Toast.LENGTH_SHORT).show();
}
});

Integer转换为Observable

1
2
3
4
5
6
7
8
//Integer转换为Observable
Observable.just(1).map(new Function<Integer, Observable<User>>() {
@Override
public Observable<User> apply(Integer integer) throws Exception {

return null;
}
});

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :