Watch LiveData from the foreground

I have a repository that contains a LiveData object and is used by both the activity and the foreground through the ViewModel. When I start observing activities, everything works as expected. However, observation from the service does not cause Observation. This is the code I'm using.

class MyService: LifecycleService() {
     lateinit var viewModel: PlayerServiceViewModel

     override fun onCreate() {
          viewModel = MyViewModel(applicationContext as Application)
     }

     override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
          viewModel.getLiveData().observe(this, Observer { data ->
            // Do something with the data
        })
     }
}

Any ideas why this is not working and I am not receiving data?

+4
source share
1 answer

I used ViewModelwith LiveDatain LifecycleActivityand Fragmentsit works and monitors the data as expected.

ViewModel Service Activity LiveData ViewModel , , DAO. DAO ViewModels, LiveData , DAO.

Dagger2 Singleton DAO . , DAO singleton, .

Services LifecycleService , .

, null

D/ForegroundService: onStartCommand: Resource{status=LOADING, message='null', data=null}
D/ForegroundService: onStartCommand: Resource{status=SUCCESS, message='null', data=TVShow(id=14,...

, Observer.

public class ForegroundService extends LifecycleService {

    private static final String TAG = "ForegroundService";

    private TVShowViewModel tvShowViewModel;
    private TVShow tvShow;

    @Inject TVShowDataRepo tvShowDataRepo;

    @Override
    public void onCreate() {
        super.onCreate();

        AndroidInjection.inject(this);
        tvShowViewModel = new TVShowViewModel(tvShowDataRepo);
        tvShowViewModel.init(14);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        tvShowViewModel.getTVShow().observe(this, tvShowResource -> {
            Log.d(TAG, "onStartCommand: " + tvShowResource);
        });
        return super.onStartCommand(intent, flags, startId);
    }
}
+4

Source: https://habr.com/ru/post/1679915/


All Articles