1

I have been struggling on this question a few days. So what I want to do on Android Slices is create slice with information which is from the back-end service. For example: on SliceProvider class

@Override
public Slice onBindSlice(Uri sliceUri) {
    l.d(TAG,"onBindSlice called");
    switch (sliceUri.getPath()) {
        case "/product":
            makeRequestForProduct();
            return createProductSlice(sliceUri);
    }
    return null;
}

and

private void makeRequestForProduct() {
    String url = Environment.getInstance().getCompleteUrl("etc..");
    RetrofitFactory.defaultBuilder(ProductWebInterface.class)
            .getProductResponse(url).enqueue(new ProductWebcallback());
}
public void onEventMainThread(ProductReceivedEvent response) {
    if (response.getProduct() != null) { //do something
    }
}

But I have no idea how to do it. Above code is not working. It is giving me an Exception.

droidhs
  • 41
  • 5

1 Answers1

0

According to Google Documentation here :

onBindSlice should return as quickly as possible so that the UI tied to this slice can be responsive. No network or other IO will be allowed during onBindSlice. Any loading that needs to be done should happen in the background with a call to ContentResolver.notifyChange(Uri, ContentObserver) when the app is ready to provide the complete data in onBindSlice.

You must therefore do your work in the background thread.

See an example below in Kotlin:

 private fun makeRequestForProductInTheBackground(sliceUri : SliceUri) {
        Completable.fromAction {
            makeRequestForProduct(sliceUri)
        }.subscribeOn(Schedulers.io()).subscribe()
 }

After the request completes you can save your data somewhere e.g a variable or a repository.

fun onEventMainThread(response: ProductReceivedEvent) {
        if (response.getProduct() != null) { 
          //Save your data in a variable or something depending on your needs
          product == response.getProduct()

          //This will call the *onBindSlice()* method again
          context?.contentResolver?.notifyChange(sliceUri, null)
        }
    }

You can then use the product data in your createProductSlice(sliceUri) method

AndroidEnthusiast
  • 6,557
  • 10
  • 42
  • 56