Skip to content

Instantly share code, notes, and snippets.

@fdoyle
Created March 6, 2014 19:42
Show Gist options
  • Save fdoyle/9397785 to your computer and use it in GitHub Desktop.
Save fdoyle/9397785 to your computer and use it in GitHub Desktop.
"asyncObservable" example
package com.example.retrofitdemo3;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.example.retrofitdemo3.api.NobelApi;
import com.example.retrofitdemo3.api.NobelService;
import com.example.retrofitdemo3.api.model.Prize;
import java.util.List;
import retrofit.RestAdapter;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.Subscriptions;
import rx.util.functions.Action1;
public class MainActivity extends Activity {
TextView textView;
Subscription s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://api.nobelprize.org/")
.setLogLevel(RestAdapter.LogLevel.BASIC)
.build();
NobelService nobelService = restAdapter.create(NobelService.class);
NobelApi nobelApi = new NobelApi(nobelService);
nobelApi.loadPrizes("economics", new Observer<List<Prize>>() {
@Override
public void onCompleted() {
Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onNext(List<Prize> prizes) {
String text = "";
for (int i = 0; i != prizes.size(); i++) {
Prize prize = prizes.get(i);
text += prize.year + " ";
for (int j = 0; j != prize.laureates.size(); j++)
text += prize.laureates.get(j).firstname + ", ";
text += "\n";
}
textView.setText(text);
}
});
Log.d("demo3", "starting");
s = Observable.create(
new Observable.OnSubscribeFunc<String>() {
@Override
public Subscription onSubscribe(Observer<? super String> observer) {
try {
Thread.sleep(5000, 0);
observer.onNext("Hello World");
} catch (InterruptedException e) {
e.printStackTrace();
observer.onError(e);
}
return Subscriptions.empty();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
new Action1<String>() {
@Override
public void call(String s) {
Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.d("demo3", "toasting");
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
}
}
);
}
@Override
protected void onDestroy() {
super.onDestroy();
s.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment