I am trying to constantly update the UI based on a long-running service output. Basically, I want to display and append a list of users one by one after they get processed by the bound service.
MainActivityViewModel
public class MainActivityViewModel extends ViewModel {
private MutableLiveData<User> user = new MutableLiveData<>();
private MutableLiveData<MyService.MyBinder> mBinder = new MutableLiveData<>();
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder iBinder) {
MyService.MyBinder binder = (MyService.MyBinder) iBinder;
mBinder.postValue(binder);
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBinder.postValue(null);
}
};
public ServiceConnection getServiceConnection(){
return serviceConnection;
}
public LiveData<User> getUser(){
return user;
}
public LiveData<MyService.MyBinder> getBinder(){
return mBinder;
}
}
My Service
public class MyService extends Service {
private final IBinder mBinder = new MyBinder();
private Handler mHandler;
@Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void starFetchingUsers(User obj){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
/**********************************************************/
Here i will be sending POST method one by one for 100 times and will get a response as a user object which needs to be a liveData. So once this object is changed after next post method, i want it to get displayed or appended on UI.
How to bind this dynamic user object variable to the MutableLiveData user created in MainActivityViewModel class? so this get auto updated in UI.
/**********************************************************/
}
});
thread.start();
}
public class MyBinder extends Binder{
MyService getService(){
return MyService.this;
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
stopSelf();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
Please let me know what I am missing in both classes.