This repository has been archived by the owner on Oct 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
1分钟掌握 ViaBus 架构的使用
KunMinX edited this page Nov 20, 2018
·
11 revisions
0. 在模块的 build.gradle 添加如下依赖
implementation "com.kunminx.viabus:viabus-core:0.4.5"
1. 定义接口,用于发送请求。
接口须继承于 IRequest,如:
public interface INoteRequest extends IRequest{
void queryList();
void insert(NoteBean bean);
...
}
2. 定义 bus,用于支持请求接口的访问。
bus 须继承于BaseBus,如:
public class NoteBus extends BaseBus {
public static INoteRequest note() {
return (INoteRequest) getRequest(INoteRequest.class);
}
...
}
3. 将 ui 注册成为响应接收者。
在 ui 中,通过 bus 发送数据请求。并在 onResult 中,依据响应码实现 ui 逻辑的处理。
public class NoteListFragment extends Fragment implements IResponse {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
...
NoteBus.registerResponseObserver(this);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
...
NoteBus.note().queryList();
}
@Override
public void onResult(Result testResult) {
String resultCode = (String) testResult.getResultCode();
switch (resultCode) {
case NoteResultCode.QUERY_LIST:
if (testResult.getResultObject() != null) {
mAdapter.setList((List<NoteBean>) testResult.getResultObject());
mAdapter.notifyDataSetChanged();
}
break;
case NoteResultCode.INSERTED:
...
}
}
@Override
public void onDestroy() {
...
NoteBus.unregisterResponseObserver(this);
}
}
4. 在模块的管理类中,将 业务 注册成为请求处理者。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
NoteBusiness noteBusiness = new NoteBusiness();
noteBusiness.init(getApplicationContext());
NoteBus.registerRequestHandler(noteBusiness);
...
}
}
5. 在业务中异步处理各种请求。
期间可发送进度消息,最后可返回结果数据。业务须继承于 BaseBusiness。
public class NoteBusiness extends BaseBusiness<NoteBus> implements INoteRequest {
@Override
public void queryList() {
handleRequest((e) -> {
List<NoteBean> list = mDataBase.getList(null, null);
...
sendMessage(e, new Result(NoteResultCode.PROGRESS, bean.getId()));
...
return new Result(NoteResultCode.QUERY_LIST, list);
});
}
@Override
public void insert(NoteBean bean) {
handleRequest((e) -> { ... });
}
...
}