我一直在尝试在Android中使用RxJava,但是我试图找出fromCallable和Just之间的区别。两者都只接收一次数据,而Create则可以多次接收数据。这是我用于实验的代码:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listenCallable();
        listenJust();
    }
    private void listenCallable() {
        CompositeDisposable compositeDisposable = new CompositeDisposable();
        Disposable disposable = Shooter.getCallable().subscribe(i -> {
            Log.d("Tag", "Listen Callable: " + i);
        });
        compositeDisposable.add(disposable);
        compositeDisposable.dispose();
    }

    private void listenJust() {
        CompositeDisposable compositeDisposable = new CompositeDisposable();
        Disposable disposable = Shooter.getJust("Jay").subscribe(i -> {
            Log.d("Tag", "Listen Just " + i);
        });
        compositeDisposable.add(disposable);
        compositeDisposable.dispose();
    }
}


以及发出数据的类:

public class Shooter {
    public static Observable<String> getCallable() {
        return Observable.fromCallable(new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {}
                return "Callable Results";
            }
        });
    }

    public static Observable<String> getJust(String input) {
        try {
            Thread.sleep(500);
        } catch (Exception e) {}
        return Observable.just("Just Results " + input);
    }
}

最佳答案

Observable.fromCallable(类似于

Observable.defer {
    try {
        Observable.just(...)
    } catch(e: Throwable) {
        Observable.error(e)
    }
}


因此,just是同步运行的,而fromCallable可以通过Scheduler推迟到另一个subscribeOn(并“稍后”执行)。

09-11 16:19