Ok I am fairly new to android and reactive programming and I have been trying for the past two days to make an activity that gets posts from a server and loads them into a Post[] that is later used in my app. The problem here is that when I pass that Post[] to the displayPostsMethod it is null. Here is the code in the Activity
public class HomeActivity extends AppCompatActivity{
private Post[] postsToDisplay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//get the posts from the server
this.getPostsFromServer();
//dispaly the posts
this.displayPosts(posts);// here are the posts null
}
public void getPostsFromServer() {
PostsProvider.getAllPosts()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(posts -> {
this.postsToDispaly = Arrays.copyOf(posts, posts.length);
});
}
}
And here is also the code from the getAllPostsMethod in PostsProvider class.
public static Observable<Post[]> getAllPosts(){
return Observable.create((ObservableEmitter<Post[]> e) -> {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("sample url")
.build();
Response response = client.newCall(request).execute();
String json = response.body().string();
Gson gson = new Gson();
Post[] posts = gson.fromJson(json, Post[].class);
e.onNext(posts);
});
}