这是我的第一个RxAndroid
。我尝试解决问题3天。
txHello无法在next()
方法上更新。它在结束循环后更新。
请帮助。
public class MainActivity extends AppCompatActivity {
TextView txHello;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.button);
txHello = findViewById(R.id.hello);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Observable<String> observer = Observable.just("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
observer.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.computation())
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
txHello.setText("------- hello world -------");
txHello.append("\nStart From thread " + Thread.currentThread().getName());
}
@Override
public void onNext(String s) {
txHello.append("\n"+s +" From thread "+ Thread.currentThread().getName());
try {
Thread.sleep(250);
} catch (InterruptedException e) {
Log.e("Thread Sleep", e.getMessage());
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
});
}
}
答案 0 :(得分:0)
Thank u very much "KuLdip PaTel" I can solve my problem with intervalRange Operator. Problem is Thread.sleep(). Like u comment.
public class MainActivity extends AppCompatActivity {
TextView txHello;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.button);
txHello = findViewById(R.id.hello);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Observable<Long> obInterval = Observable.intervalRange(0L, 10, 0, 500, TimeUnit.MILLISECONDS);
obInterval.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(id -> {
txHello.setText("------- hello world -------");
})
.doOnNext(id -> {
txHello.append("\n" + id + " Run From thread " + Thread.currentThread()
.getName());
})
.doOnComplete(() -> {
txHello.append("------- ending process -------");
})
.subscribe();
}
});
}
}