Created
April 29, 2014 19:26
-
-
Save joesteele/30b371fca2766a8b930a to your computer and use it in GitHub Desktop.
Sample Activity to fetch tweets from Twitter, store them in the db, then return the results on the main thread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends ListActivity { | |
private TweetAdapter adapter; | |
private Subscription subscription; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
adapter = new TweetAdapter(this); | |
setListAdapter(adapter); | |
loadTweets(); | |
} | |
private void loadTweets() { | |
final AlertDialog dialog = SimpleProgressDialog.create(this, "Loading Tweets..."); | |
dialog.show(); | |
subscription = Loader.loadAndSyncTweets(this) | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe(new Observer<List<Tweet>>() { | |
@Override | |
public void onCompleted() { | |
dialog.dismiss(); | |
} | |
@Override | |
public void onError(Throwable e) { | |
Log.e("MainActivity", "Uh oh! Error loading tweets: " + e.getCause().getMessage()); | |
dialog.dismiss(); | |
} | |
@Override | |
public void onNext(List<Tweet> tweets) { | |
adapter.replaceWith(tweets); | |
dialog.dismiss(); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is from a sample skeleton Android app I have I use for experimenting.
That loader static method (
Loader.loadAndSyncTweets
) will:A: load local tweets from the db in the background and return them to the UI on the main thread
B: fetch the tweets from the API in the background
C: store those freshly fetched tweets in the db in the background
D: return the new/fresh tweets to the UI on the main thread
This is a pretty common use case for client applications that interface with an API, and using RxJava makes it easy to hide all that stuff and create a more elegant client API to interface with.