当前位置: 首页>>代码示例>>Java>>正文


Java Observer类代码示例

本文整理汇总了Java中android.arch.lifecycle.Observer的典型用法代码示例。如果您正苦于以下问题:Java Observer类的具体用法?Java Observer怎么用?Java Observer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Observer类属于android.arch.lifecycle包,在下文中一共展示了Observer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: onCreate

import android.arch.lifecycle.Observer; //导入依赖的package包/类
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_holder);
    tvUsername = findViewById(R.id.tv_username);
    tvAddress = findViewById(R.id.tv_address);

    mDemoViewHolder = ViewModelProviders.of(this).get(DemoViewHolder.class);

    mDemoViewHolder.getUserInfo().observe(this, new Observer<UserEntity>() {
        @Override
        public void onChanged(@Nullable UserEntity userEntity) {
            if (userEntity == null) {
                return;
            }
            tvUsername.setText(userEntity.getUsername());
            tvAddress.setText(userEntity.getAddress());
        }
    });
}
 
开发者ID:jingle1267,项目名称:AndroidArchitectureComponets,代码行数:21,代码来源:ViewHolderActivity.java

示例2: getValue

import android.arch.lifecycle.Observer; //导入依赖的package包/类
/**
 * Get the value from a LiveData object. We're waiting for LiveData to emit, for 2 seconds.
 * Once we got a notification via onChanged, we stop observing.
 */
public static <T> T getValue(final LiveData<T> liveData) throws InterruptedException {
  final Object[] data = new Object[1];
  final CountDownLatch latch = new CountDownLatch(1);
  Observer<T> observer = new Observer<T>() {
    @Override
    public void onChanged(@Nullable T o) {
      data[0] = o;
      latch.countDown();
      liveData.removeObserver(this);
    }
  };
  liveData.observeForever(observer);
  latch.await(2, TimeUnit.SECONDS);
  //noinspection unchecked
  return (T) data[0];
}
 
开发者ID:mapbox,项目名称:mapbox-plugins-android,代码行数:21,代码来源:LiveDataTestUtil.java

示例3: initData

import android.arch.lifecycle.Observer; //导入依赖的package包/类
@Override
public void initData(Bundle savedInstanceState) {
    mViewDataBinding.rvTeam.addItemDecoration(new DividerItemDecoration(getThis(), DividerItemDecoration.VERTICAL));
    mViewDataBinding.rvTeam.setAdapter(mAdapter);
    if (getArguments() != null) {
        int seasion = getArguments().getInt("Seasion ID");
        mSeasionName = getArguments().getString("Seasion Name");
        mViewModel.getResults(seasion).observe(this, new Observer<Resource<List<TeamModel>>>() {
            @Override
            public void onChanged(@Nullable Resource<List<TeamModel>> listResource) {
                mViewDataBinding.setResource(listResource);
                mViewDataBinding.executePendingBindings();
                if (listResource != null && listResource.data != null) {
                    mAdapter.updateData(listResource.data);
                }
            }
        });
    }

}
 
开发者ID:NamTranDev,项目名称:CleanArchitechture,代码行数:21,代码来源:TeamMvvmFragment.java

示例4: onCreate

import android.arch.lifecycle.Observer; //导入依赖的package包/类
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DaggerAppComponent.builder()
            .appModule(new AppModule(getApplication()))
            .roomModule(new RoomModule(getApplication()))
            .build()
            .inject(this);


    productRepository.findAll().observe(this, new Observer<List<Product>>() {
        @Override
        public void onChanged(@Nullable List<Product> products) {
            Toast.makeText(MainActivity.this, String.format("Product size: %s", products.size()), Toast.LENGTH_SHORT).show();
        }
    });
}
 
开发者ID:mcatta,项目名称:RoomDagger2Demo,代码行数:20,代码来源:MainActivity.java

示例5: onCreateView

import android.arch.lifecycle.Observer; //导入依赖的package包/类
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_org, container, false);
    RecyclerView recyclerView = view.findViewById(R.id.rv_org);
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    float width = displayMetrics.widthPixels / displayMetrics.density;
    final int spanCount = (int) (width / 180.00);
    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL));
    orgAdapter = new OrgAdapter();
    recyclerView.setAdapter(orgAdapter);
    organizationViewModel = ViewModelProviders.of(getActivity()).get(OrganizationViewModel.class);
    setHasOptionsMenu(true);
    organizationViewModel.getOrganizations().observe(this, new Observer<PagedList<Organization>>() {
        @Override
        public void onChanged(@Nullable PagedList<Organization> organizations) {
            orgPagedList = organizations;
            orgAdapter.setList(orgPagedList);
            view.findViewById(R.id.progressBar).setVisibility(View.GONE);
        }
    });

    return view;
}
 
开发者ID:coding-blocks,项目名称:GSoC-Info-Android,代码行数:25,代码来源:OrganizationFragment.java

示例6: onCreate

import android.arch.lifecycle.Observer; //导入依赖的package包/类
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_live_data);

    tvUsername = findViewById(R.id.tv_username);

    username = new MutableLiveData<>();

    username.observe(this, new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            tvUsername.setText(s);
        }
    });
}
 
开发者ID:jingle1267,项目名称:AndroidArchitectureComponets,代码行数:17,代码来源:LiveDataActivity.java

示例7: getUser

import android.arch.lifecycle.Observer; //导入依赖的package包/类
@Test
public void getUser() {
    User userEntity = new User("[email protected]", "John", "Doe");
    com.jonathanpetitfrere.mvvm.repository.api.model.User userModel = mapper.toModel(userEntity);

    when(transformers.applySchedulersToFlowable()).thenReturn(flowable -> flowable);
    when(userDao.loadUser(anyString())).thenReturn(Flowable.just(userEntity));
    when(userApi.getUser(anyString())).thenReturn(Flowable.just(userModel));

    Observer<User> observer = mock(Observer.class);

    userRepository.getUser(anyString())
            .observeForever(observer);

    verify(userDao, times(1)).loadUser(anyString());
    verify(userApi, times(1)).getUser(anyString());
    verify(userDao, times(1)).saveUser(userEntity);
    verify(observer, only()).onChanged(userEntity);
}
 
开发者ID:Jon6193,项目名称:Android-MVVM,代码行数:20,代码来源:UserRepositoryTest.java

示例8: getUsers

import android.arch.lifecycle.Observer; //导入依赖的package包/类
@Test
public void getUsers() {
    User userEntityOne = new User("[email protected]", "John", "Doe");
    User userEntityTwo = new User("[email protected]", "Jane", "Doe");

    List<User> userEntities = new ArrayList<>();
    List<com.jonathanpetitfrere.mvvm.repository.api.model.User> userModels = new ArrayList<>();

    userEntities.add(userEntityOne);
    userEntities.add(userEntityTwo);
    userModels.add(mapper.toModel(userEntityOne));
    userModels.add(mapper.toModel(userEntityTwo));

    when(transformers.applySchedulersToFlowable()).thenReturn(flowable -> flowable);
    when(userDao.loadUsers()).thenReturn(Flowable.just(userEntities));
    when(userApi.getUsers()).thenReturn(Flowable.just(userModels));

    Observer<List<User>> observer = mock(Observer.class);

    userRepository.getUsers()
            .observeForever(observer);

    verify(userDao, times(userEntities.size())).saveUser(any());
    verify(userApi, times(1)).getUsers();
    verify(observer, only()).onChanged(userEntities);
}
 
开发者ID:Jon6193,项目名称:Android-MVVM,代码行数:27,代码来源:UserRepositoryTest.java

示例9: observerPersonListResults

import android.arch.lifecycle.Observer; //导入依赖的package包/类
private void observerPersonListResults(LiveData<List<Person>> personsLive) {
    //observer LiveData
    personsLive.observe(this, new Observer<List<Person>>() {
        @Override
        public void onChanged(@Nullable List<Person> person) {
            if(person == null){
                return;
            }
            Toast.makeText(MainActivity.this, "Number of person objects in the response: "+person.size(), Toast.LENGTH_LONG).show();
        }
    });
}
 
开发者ID:srinurp,项目名称:AndroidRoom,代码行数:13,代码来源:MainActivity.java

示例10: ClaimItemAdapter

import android.arch.lifecycle.Observer; //导入依赖的package包/类
public ClaimItemAdapter(
        final Context context,
        final LifecycleOwner owner,
        final LiveData<List<ClaimItem>> liveItems) {

    this.layoutInflater = LayoutInflater.from(context);
    this.itemPresenter = new ItemPresenter(context);

    liveItems.observe(owner, new Observer<List<ClaimItem>>() {
        @Override
        public void onChanged(final List<ClaimItem> claimItems) {
            if (!items.isEmpty()) {
                updateCommand.exec(Pair.create(items, claimItems));
            } else {
                createDisplayListCommand.exec(claimItems);
            }
        }
    });
}
 
开发者ID:PacktPublishing,项目名称:Hands-On-Android-UI-Development,代码行数:20,代码来源:ClaimItemAdapter.java

示例11: ClaimItemAdapter

import android.arch.lifecycle.Observer; //导入依赖的package包/类
public ClaimItemAdapter(
        final Context context,
        final LifecycleOwner owner,
        final LiveData<List<ClaimItem>> liveItems) {

    this.layoutInflater = LayoutInflater.from(context);
    this.itemPresenter = new ItemPresenter(context);

    liveItems.observe(owner, new Observer<List<ClaimItem>>() {
        public void onChanged(final List<ClaimItem> claimItems) {
            ClaimItemAdapter.this.items = (claimItems != null)
                    ? claimItems
                    : Collections.<ClaimItem>emptyList();

            ClaimItemAdapter.this.notifyDataSetChanged();
        }
    });
}
 
开发者ID:PacktPublishing,项目名称:Hands-On-Android-UI-Development,代码行数:19,代码来源:ClaimItemAdapter.java

示例12: AllowanceOverviewPresenter

import android.arch.lifecycle.Observer; //导入依赖的package包/类
public AllowanceOverviewPresenter(
        final LifecycleOwner lifecycleOwner,
        final int allowance) {

    ClaimApplication.getClaimDatabase()
            .claimItemDao()
            .selectAll()
            .observe(lifecycleOwner, new Observer<List<ClaimItem>>() {
                @Override
                public void onChanged(final List<ClaimItem> claimItems) {
                    updateSpendStatsCommand.exec(claimItems);
                }
            });

    this.allowance.set(allowance);
}
 
开发者ID:PacktPublishing,项目名称:Hands-On-Android-UI-Development,代码行数:17,代码来源:AllowanceOverviewPresenter.java

示例13: getValue

import android.arch.lifecycle.Observer; //导入依赖的package包/类
public static <T> T getValue(LiveData<T> liveData) throws InterruptedException {
    final Object[] data = new Object[1];
    CountDownLatch latch = new CountDownLatch(1);
    Observer<T> observer = new Observer<T>() {
        @Override
        public void onChanged(@Nullable T o) {
            data[0] = o;
            latch.countDown();
            liveData.removeObserver(this);
        }
    };
    liveData.observeForever(observer);
    latch.await(2, TimeUnit.SECONDS);
    //noinspection unchecked
    return (T) data[0];
}
 
开发者ID:duyp,项目名称:mvvm-template,代码行数:17,代码来源:LiveDataTestUtil.java

示例14: subscribe

import android.arch.lifecycle.Observer; //导入依赖的package包/类
private void subscribe() {
  viewModel.geocodingLiveData.observe(this, new Observer<GeocodingResponse>() {
    @Override
    public void onChanged(@Nullable GeocodingResponse geocodingResponse) {
      updateSearchResultView(geocodingResponse);
    }
  });

  // Subscribe to the search history database
  DataRepository.getInstance(viewModel.getDatabase()).getSearchHistory().observe(this,
    new Observer<List<SearchHistoryEntity>>() {
      @Override
      public void onChanged(@Nullable List<SearchHistoryEntity> searchHistoryEntities) {
        updateSearchHistoryView(searchHistoryEntities);
      }
    });
}
 
开发者ID:mapbox,项目名称:mapbox-plugins-android,代码行数:18,代码来源:PlaceAutocompleteFragment.java

示例15: basicFromNetwork

import android.arch.lifecycle.Observer; //导入依赖的package包/类
@Test
public void basicFromNetwork() {
    AtomicReference<Foo> saved = new AtomicReference<>();
    shouldFetch = Objects::isNull;
    Foo fetchedDbValue = new Foo(1);
    saveCallResult = foo -> {
        saved.set(foo);
        dbData.setValue(fetchedDbValue);
        return null;
    };
    final Foo networkResult = new Foo(1);
    createCall = (aVoid) -> ApiUtil.createCall(Response.success(networkResult));

    Observer<Resource<Foo>> observer = Mockito.mock(Observer.class);
    networkBoundResource.asLiveData().observeForever(observer);
    drain();
    verify(observer).onChanged(Resource.loading(null));
    reset(observer);
    dbData.setValue(null);
    drain();
    assertThat(saved.get(), is(networkResult));
    verify(observer).onChanged(Resource.success(fetchedDbValue));
}
 
开发者ID:VivekNeel,项目名称:CricKotlin,代码行数:24,代码来源:NetworkBoundResourceTest.java


注:本文中的android.arch.lifecycle.Observer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。