android - 如何实现对可运行线程的简单 RxJava 调用?

标签 android rx-java rx-android

我尝试将一个简单的 RxJava 调用添加到一个可运行的线程中,这样我就可以在线程完成后更新 UI。我该怎么做呢?这是我的 Activity 代码:

public class PrintActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_printer);
        printZpl("^XA^LL360^POI^FO20,20^A0N,25,25^FDThis is a test of the ZPL file printing on " + Helper.getCurrDateTime() + "^FS^XZ");
    }
}

这是执行可运行线程的类:

public class PrinterManager {
    private static void printZpl(final String body, final String footer) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    Connection btCon = new BluetoothConnectionInsecure("AC:3F:A4:0E:22:05");
                    btCon.open();
                    btCon.write(body.getBytes());
                    Thread.sleep(500);
                    btCon.close();
                    // Insert RxJava return here to update the UI in the activity once the thread is completed.
                } catch (Exception e) {
                    Timber.e(e.getMessage());
                }
            }
        }).start();
    }
}

我简化了这篇文章的代码。实际代码要复杂得多......

最佳答案

使用 RxJava2:

Completable.fromAction(() -> {
            Connection btCon = new BluetoothConnectionInsecure("AC:3F:A4:0E:22:05");
            btCon.open();
            btCon.write(body.getBytes());
            Thread.sleep(500);
            btCon.close();
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();

使用 Completable 而不是 Observable 因为除了完成事件你不会发出任何东西。

关于android - 如何实现对可运行线程的简单 RxJava 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47211815/

相关文章:

java - RxJava 将新对象添加到流中

android - 如何在 recyclerview 中执行多选?

android - 更改自定义工具栏文本

android - 带有 Android SDK 的 Eclipse 缺少菜单项

android - 错误转换 observable.subscribe

android - 如何从android中的retrofit 2和rxjava获取xml数据

android - 尽管我安装了驱动程序,但 adb 无法检测到 Sony Xperia s

java - RXJava逻辑图链

android - RxJava 的 RxSwift Variable 或 BehaviourRelay 的内置等效项

java - 如何使用 RxJava 和 RxAndroid 获取带条件的 map ?